节流的核心思想是:在一定时间间隔内,无论事件触发多少次,只执行一次函数,节流会稀释函数的执行频率。
应用场景
- 滚动事件(每隔一段时间检查滚动位置)。
- 按钮点击(防止用户快速多次点击)。
手写实现
时间戳
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function throttle(func, delay) { let lastTime = 0;
return function (...args) { const context = this; const now = Date.now();
if (now - lastTime >= delay) { func.apply(context, args); lastTime = now; } }; }
|
定时器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function throttle(func, delay) { let timer = null;
return function (...args) { const context = this;
if (timer) return;
timer = setTimeout(() => { func.apply(context, args);
timer = null; }, delay); }; }
|
通过手写,可以更好地理解它们的原理和应用场景。在实际开发中,请直接使用 Lodash 等工具库提供的 throttle
方法。
1
| _.throttle(func, [wait=0], [options=])
|