节流与防抖
节流与防抖分别限制什么?
- 节流: 固定时间段内最多执行一次, 适合滚动与拖拽等高频事件;
- 防抖: 固定时间段内只执行最后一次, 适合搜索输入与窗口缩放结束后的处理;
如何手写节流?
const throttle = (fun, wait) => {
let timeoutID = null;
return function (...args) {
if (timeoutID) return; // 冷却中直接丢弃
timeoutID = setTimeout(() => {
fun.apply(this, args);
timeoutID = null;
}, wait);
};
};
- 变体: 立即执行版在首次调用时马上执行, 再进入冷却;
- 返回函数: 用闭包保存
timeoutID, 依赖见 闭包;
如何手写防抖?
const debounce = (fun, wait) => {
let timeoutID = null;
return function (...args) {
if (timeoutID) clearTimeout(timeoutID); // 重新计时
timeoutID = setTimeout(() => {
fun.apply(this, args);
}, wait);
};
};
- 关键: 每次调用先清除上一个定时器, 只有最后一次能在
wait之后触发; - 实践: 需要保留
this与参数时用fun.apply(this, args), 不要直接传函数引用;