js节流实现
节流的概念
节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。
基础实现方法
使用时间戳判断是否执行函数:
function throttle(func, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(this, args);
lastTime = now;
}
};
}
定时器实现方法
使用setTimeout控制执行间隔:
function throttle(func, delay) {
let timer = null;
return function(...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
结合时间戳和定时器
实现首次立即执行和尾调用保证:
function throttle(func, delay) {
let lastTime = 0;
let timer = null;
return function(...args) {
const now = Date.now();
const remaining = delay - (now - lastTime);
if (remaining <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
func.apply(this, args);
lastTime = now;
} else if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
lastTime = Date.now();
}, remaining);
}
};
}
使用场景示例
窗口滚动事件处理:
window.addEventListener('scroll', throttle(() => {
console.log('处理滚动事件');
}, 200));
注意事项
- 时间间隔delay需要根据实际场景调整
- 注意this绑定问题,使用箭头函数或apply/call确保上下文正确
- 节流函数返回的新函数需要保持引用才能正确工作







