节流js实现
节流(Throttle)的 JavaScript 实现
节流是一种限制函数执行频率的技术,确保函数在指定时间间隔内最多执行一次。适用于高频触发的事件(如滚动、鼠标移动等)。
基本实现原理
通过时间戳或定时器控制函数执行频率。以下是两种常见的实现方式:

时间戳版本

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 || remaining > delay) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
func.apply(this, args);
lastTime = now;
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
lastTime = Date.now();
}, remaining);
}
};
}
使用示例
const throttledScrollHandler = throttle(() => {
console.log('Scroll event throttled');
}, 200);
window.addEventListener('scroll', throttledScrollHandler);
注意事项
- 节流时间间隔需根据实际场景调整,过短可能无法达到性能优化效果,过长可能影响用户体验。
- 如果函数需要返回值,需额外处理(通常节流函数不直接返回结果)。
- 确保清除定时器以避免内存泄漏。






