最基础版本的防抖函数。
function debounce(fn, delay) {
// arguments
let timer = null;
const _debounce = function(...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
return _debounce;
};
第一次立即执行的防抖函数。
function debounce(fn, delay, out = false) {
let timer = null;
let isOut = false;
let _debounce = function(...args) {
if (timer) clearTimeout(timer);
if (out && !isOut) {
fn.apply(this, args);
isOut = true;
} else {
timer = setTimeout(() => {
fn.apply(this, args);
isOut = false;
}, delay);
}
}
return _debounce;
}