两者都是在一段时间内连续触发同一事件而为了避免事件处理函数频繁连续的调用而采取的解决方案。
防抖就是合并一段时间内连续的触发的事件
而节流控制相同事件之间必须要具有一定的时间间隔
打个比方,假如同一事件在10秒内触发了N次,如果采用防抖的方案,那么事件处理函数在10秒内只会触发一次。而如果采用节流的方案,可能就是在每间隔1秒的地方触发一次。
防抖的代码:
function debounce(fn, wait) {
let timer = null;
return () => {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => fn(), wait);
};
}
节流:
function throttle(fn, delay) {
let pre = null;
return () => {
const now = Date.now();
if (pre !== null && now - pre < delay) {
return ;
}
fn();
pre = now;
}
}
原文:https://www.cnblogs.com/freesfu/p/14671704.html