防抖
const input1 = document.getElementById('input1')
let timer = null
input1.addEventListener('keyup', function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
// 模拟触发 change 事件
console.log(input1.value)
// 清空定时器
timer = null
}, 500)
})
// =======================
// 封装防抖
function debounce(fn, delay = 500) {
// timer 是闭包中的
let timer = null
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
input1.addEventListener('keyup', debounce(function (e) {
console.log(e.target)
console.log(input1.value)
}, 600))
节流
const div1 = document.getElementById('div1')
let timer = null
div1.addEventListener('drag', function (e) {
if (timer) {
return
}
timer = setTimeout(() => {
console.log(e.offsetX, e.offsetY)
timer = null
}, 100)
})
// ===========================
// 封装节流
function throttle(fn, delay = 100) {
let timer = null
return function () {
if (timer) {
return
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
div1.addEventListener('drag', throttle(function (e) {
console.log(e.offsetX, e.offsetY)
}))
div1.addEventListener('drag', function(event) {
})