当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
根据定义我们实现第一版防抖函数。
function debounce(func, wait) {
let timer = null
let context = this
let args = arguments
const debounced = function () {
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(function () {
func.apply(context, args)
}, wait)
}
return debounced
}
我们希望立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。基于此我们得到下面的代码:
function debounce(func, wait, immediate) {
let timer = null
let context = this
let args = arguments
const debounced = function () {
if (timer) {
clearTimeout(timer)
timer = null
}
if (immediate) {
const callNow = !timer
timer = setTimeout(function () {
clearTimeout(timer)
timer = null
}, wait)
callNow && func.apply(context, args)
} else {
timer = setTimeout(function () {
func.apply(context, args)
}, wait)
}
}
return debounced
}
ok, 接下来我们希望在执行过程中可以能取消 debounce 函数
function debounce(func, wait, immediate) {
// ...省略代码
debounced.cancel = function() {
clearTimeout(timer);
timer = null;
};
return debounced
}