手写防抖(debounce)和节流(throttle)带配置
请手写实现带immediate和leading/trailing配置的防抖和节流函数。
回答
苦行僧
function debounce(fn, delay = 300, immediate = false) {
let timer = null;
return function(...args) {
const callNow = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (!immediate) fn.apply(this, args);
}, delay);
if (callNow) fn.apply(this, args);
};
}
function throttle(fn, delay = 300, options = { leading: true, trailing: true }) {
let timer = null, lastArgs = null;
return function(...args) {
const context = this;
if (!timer) {
if (options.leading) fn.apply(context, args);
timer = setTimeout(() => {
timer = null;
if (options.trailing && lastArgs) {
fn.apply(context, lastArgs);
lastArgs = null;
}
}, delay);
} else {
lastArgs = args;
}
};
}
区别:防抖等待静止后才执行;节流保证固定时间间隔执行。