实现防抖和节流的函数
参考答案
防抖(debounce):停止触发 delay 后才执行
function debounce(fn, delay = 300, immediate = false) {
let timer = null;
return function (...args) {
const ctx = this;
if (timer) clearTimeout(timer);
if (immediate && !timer) fn.apply(ctx, args);
timer = setTimeout(() => { timer = null; if (!immediate) fn.apply(ctx, args); }, delay);
};
}
节流(throttle):固定间隔最多执行一次
function throttle(fn, interval = 300, { leading = true, trailing = true } = {}) {
let last = 0, timer = null;
return function (...args) {
const now = Date.now(), ctx = this;
if (leading && now - last >= interval) { last = now; fn.apply(ctx, args); }
else if (trailing && !timer) {
timer = setTimeout(() => { timer = null; last = Date.now(); fn.apply(ctx, args); }, interval - (now - last));
}
};
}
区别:防抖"只执行最后一次",节流"定期执行";分别适合输入搜索、滚动/resize。可加 cancel()/flush() 与 this、参数透传。