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;
}
};
}
特点
- 首次触发立即执行(时间差为0)。
- 最后一次触发可能不执行(若时间间隔未达到)。
定时器实现方式
通过定时器控制函数执行,确保延迟时间内仅触发一次。
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);
lastTime = Date.now();
timer = null;
}, remaining);
}
};
}
特点
- 首次触发立即执行。
- 最后一次触发延迟执行(剩余时间内)。
应用示例
监听滚动事件并使用节流优化:

const handleScroll = throttle(() => {
console.log('Scroll event throttled');
}, 200);
window.addEventListener('scroll', handleScroll);
注意事项
this绑定:确保函数内this正确指向,通过apply或箭头函数处理。- 参数传递:使用剩余参数(
...args)保留原始事件参数。 - 取消节流:可扩展实现取消定时器的逻辑(如
throttle.cancel())。
与防抖(Debounce)的区别
- 节流:固定间隔内执行一次(均匀分布)。
- 防抖:停止触发后延迟执行(最后一次有效)。






