节流的核心是在指定时间间隔内函数最多执行一次,适合resize、scroll等高频事件;基础实现用时间戳控制,增强版支持leading选项控制首次是否立即执行,尾部执行通常用防抖更合适。

节流(Throttle)的核心是:**在指定时间间隔内,函数最多执行一次**。适合处理高频触发事件(如 resize、scroll、mousemove),避免过度调用。
基础实现:使用时间戳
记录上一次执行的时间,每次触发时对比当前时间,超过间隔才执行并更新时间戳。
适用场景:首次立即执行,后续按固定间隔执行
function throttle(func, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(this, args);
lastTime = now;
}
};
}
增强版:支持首次是否立即执行
通过选项 leading 控制第一次是否立刻执行(默认 true),更灵活。
function throttle(func, delay, options = {}) {
const { leading = true } = options;
let lastTime = 0;
let timer = null;
<p>return function(...args) {
const now = Date.now();</p><pre class="brush:php;toolbar:false;">if (!lastTime && leading) {
func.apply(this, args);
lastTime = now;
return;
}
if (now - lastTime >= delay) {
func.apply(this, args);
lastTime = now;
}}; }
带尾部执行的节流(可选)
有些场景希望“最后一次触发也得响应”,可加 trailing 选项(需配合定时器清理逻辑)。但注意:它和纯时间戳版有行为差异,通常用防抖更合适。若坚持节流+尾部,建议用定时器方案:
- 触发时清空旧定时器
- 设置新定时器,在 delay 后执行(保证至少一次延迟执行)
- 结合 leading/trailing 判断是否立即执行或延迟执行
不过多数业务场景,时间戳版已足够——简洁、无副作用、易于理解。











