js throttle实现
实现 JavaScript 的 throttle(节流)函数
节流(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 timer = null;
return function(...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
结合时间戳和定时器的优化版
结合两种方式的优点,确保首次立即执行且最后一次触发也会执行:
function throttle(func, delay) {
let timer = null;
let lastTime = 0;
return function(...args) {
const now = Date.now();
const remaining = delay - (now - lastTime);
if (remaining <= 0 || remaining > delay) {
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);
}
};
}
使用示例
const throttledScrollHandler = throttle(() => {
console.log('Scroll event throttled');
}, 200);
window.addEventListener('scroll', throttledScrollHandler);
注意事项
- 时间戳版本会立即执行第一次调用,但可能忽略最后一次触发。
- 定时器版本会确保最后一次触发被执行,但首次调用会有延迟。
- 优化版结合了两者的优点,但代码复杂度稍高。
- 注意清除定时器避免内存泄漏。






