//防抖函数(函数名,时间,是否立即实行)
function debounce(func, wait, immediate) {
let timeout, result;
let debounced = function () {
//改变this指向
let _this = this;
//改变event指向
let args = arguments;
clearTimeout(timeout);
if (immediate) {
//立即执行
let callnow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callnow) {
result = func.apply(_this, args);
}
} else {
//延迟执行
timeout = setTimeout(function () {
func.apply(_this, args);
}, wait);
}
return result;
}
//取消操作
debounced.cancel = function () {
clearTimeout(timeout);
timeout = null;
}
return debounced;
}