手写防抖debounce
防抖debounce
- 监听一个输入框文件变化后触发change事件
- 直接用keyup事件,则会频繁触发change事件
- 防抖:用户输入结束或暂停,才会触发chage事件
思路:监听keyup事件,每次keyup事件都产生一个定时器事件,延后一定时间。当新的keyup事件进来,就取消上次的定时器事件,达到只触发最后一次停留时间较长的keyup事件
// 防抖
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))