节流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;
}
};
}
定时器实现方式
保证最后一次触发能执行:
function throttle(func, delay) {
let timeoutId = null;
return function(...args) {
if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
}, delay);
}
};
}
结合时间戳和定时器
更完善的实现方式:

function throttle(func, delay) {
let lastTime = 0;
let timeoutId = null;
return function(...args) {
const now = Date.now();
const remaining = delay - (now - lastTime);
if (remaining <= 0) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
func.apply(this, args);
lastTime = now;
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args);
lastTime = Date.now();
timeoutId = null;
}, remaining);
}
};
}
使用方法示例
const throttledScrollHandler = throttle(() => {
console.log('Scroll event throttled');
}, 200);
window.addEventListener('scroll', throttledScrollHandler);
注意事项
- 节流时间间隔需要根据实际场景调整
- 在组件卸载时需要清除事件监听
- 箭头函数会改变this绑定,需要注意上下文
- 高频事件节流能显著提升性能






