节流实现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 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('Scroll event throttled');
}, 200));
注意事项
- 时间戳方式会立即执行第一次调用,但后续调用会被限制
- 定时器方式会在延迟结束后执行,但第一次调用也会延迟
- 结合方式能确保首次立即执行,最后一次也会执行






