发布于 1年前
JS 函数防抖
const debounce = function debounce(func, wait, immediate) {
if (typeof func !== "function") throw new TypeError('func must be an function');
if (typeof wait === "boolean") {
immediate = wait;
wait = 300;
}
if (typeof wait !== "number") wait = 300;
if (typeof immediate !== "boolean") immediate = false;
let timer;
return function proxy(...params) {
let runNow = !timer && immediate,
self = this,
result;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (!immediate) result = func.call(self, ...params);
}, wait);
if (runNow) result = func.call(self, ...params);
return result;
};
};