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);
}
};
}
使用场景示例
监听滚动事件并节流处理:
const handleScroll = throttle(() => {
console.log('Scroll event throttled');
}, 200);
window.addEventListener('scroll', handleScroll);
注意事项
- 节流时间间隔(
delay)需要根据实际场景调整,过短可能无法达到节流效果,过长会影响用户体验。 - 如果函数执行时间较长,可能需要结合防抖(debounce)或其他优化手段。
- 在React/Vue等框架中,可直接使用
lodash.throttle等工具库简化实现。







