防抖函数怎么取消防抖?
这个取消防抖啥意思,就是比如点击按钮取消防抖,那就是立即输出的意思吗?
function debounce(func, wait, immediate) {
var timer;
// 检查函数
if (typeof func !== 'function') {
throw new TypeError('Expected a function');
}
// 保证wait存在
wait = +wait || 0;
const debounced = function () {
var _this = this;
var args = arguments;
if (timer) clearTimeout(timer); // 常规流程,间隔内触发时清掉重置定时
if (immediate) {
// 如果已经执行过,不再执行
var callNow = !timer; // 如果不存在定时器,则callNow为true
timer = setTimeout(function () {
timer = null; // 为了保证之后的时效性,手动添加timer
}, wait)
// 因为不存在timer,证明是首次执行,所以直接调用
if (callNow) func.apply(_this, args)
}
else {
timer = setTimeout(function () {
func.apply(_this, args)
}, wait);
}
}
const cancel = function(){
clearTimeout(timer);
timer = null;
}
const pending = function(){
return timer !== undefined;
}
debounced.cancel = cancel;
debounced.pending = pending;
return debounced
}
防抖是美女先用婚约吊着舔狗的胃口,如果婚约到期还没有新的人来舔,美女就会嫁给眼前人,如果有新人来就毫不犹豫取消原定的婚约,另立新约。
这里的取消就是取消当前的婚约,取消之后这个美女也就不知所踪,就像很多有头无尾的故事的主角一样。
但是历史总会重演,新的美女将与新的舔狗在新的时空里重生。