一定时间之内, 函数被重复触发, 只会执行一次. 原理: 将函数放到定时器中执行, 没有到定时器设置的时间, 再次触发,清除定时器, 重新计时
用户输入内容
const input = document.getElementById('search')
input.addEventListener('keyup', function() {
console.log('keyup')
})
使用定时器进行优化
// 记录定时器id
let timer = null
input.addEventListener('keyup', function () {
// 清除上一次的定时器
timer && clearTimeout(timer)
// 新建一个定时器
timer = setTimeout(() => {
console.log('keyup')
}, 3000)
})
每一次触发, 判断之前是否进行过调用, 如果有清除掉 新建一个定时器, 存放最新的调用
封装方法
防抖工具函数
// fn 待处理的方法
// interval 延迟时间
// 返回值 返回有防抖功能的函数
function shake(fn, interval = 1000) {
let timer = null
return function () {
const args = arguments
// 清除上一次的定时器
timer && clearTimeout(timer)
timer = setTimeout(() => {
// 调用方法fn, 参数是args
fn.apply(this, args)
}, interval)
}
}
- 使用1
function inputKeyupFn() {
console.log('keyup')
}
const input = document.getElementById('search')
const inputKeyupFnShake = shake(inputKeyupFn, 2000)
input.addEventListener('keyup', inputKeyupFnShake)
- 使用2
fuction custom(opt) {
console.log(opt)
}
const customShake = shake(custom, 3000)
customShake('custom')