我听过最好的对节流和防抖的形容就是把它们看成游戏中的技能冷却和TP,技能释放之后会产生CD,等冷却完成之后才可以继续释放,而防抖是看成回城,受到攻击打断之后在重新倒计时。
节流 Throttle
const throttle = (fn, time) => {
const 冷却中 = false;
return (...args) => {
if (冷却中) return;
fn.call(undefined, ...args);
冷却中 = true;
setTimeout(() => {
冷却中 = false;
}, time);
};
};
防抖 Debounce
const debounce = (fn, time) => {
let 回城计时器 = null;
return (...args) => {
if (回城计时器 !== null) {
clearTimeout(回城计时器);
}
回城计时器 = setTimeout(() => {
fn.call(undefined, ...args);
回城计时器 = null;
}, time);
};
};