js 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) {
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);
注意事项
- 时间间隔的选择应根据实际需求调整
- 确保清除定时器以避免内存泄漏
- 考虑是否需要保留最后一次触发
这些实现方式可以根据具体需求选择使用,第一种实现最简单,第三种实现最完整。






