防抖
- 防止抖动,即间隙过程后,再执行下一步;
- eg:搜索框输入,等停止输入后再触发搜索
function debounce(callback, delay = 200) {
let timer = 0;
return function () {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
callback.apply(this, arguments);
timer = 0; // 重新计时
}, delay)
}
}
节流
- 节省交互沟通
- eg:drag 和 scroll 期间触发某个回调,需设置一个时间间隔;
function throttle(callback, delay = 200) {
let timer = 0;
return function () {
if (timer) return;
timer = setTimeout(() => {
callback.apply(this, arguments);
timer = 0;
}, delay)
}
}
总结
- 节流:限制执行频率,有节奏的执行;
- 防抖:限制执行次数,多次密集的触发只执行一次;
- 节流关注「过程」,防抖关注「结果」。