throttle js实现

throttle 函数实现
节流(throttle)是一种限制函数执行频率的技术,确保函数在指定时间间隔内最多执行一次。常用于优化滚动、窗口调整等高频事件。
基础实现
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
return func.apply(this, args);
};
}
包含 leading 和 trailing 选项的增强版
function throttle(func, delay, options = {}) {
let timeoutId, lastCall = 0;
const { leading = true, trailing = true } = options;
return function(...args) {
const now = Date.now();
const context = this;
if (!lastCall && !leading) lastCall = now;
const remaining = delay - (now - lastCall);
if (remaining <= 0 || remaining > delay) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
lastCall = now;
func.apply(context, args);
} else if (!timeoutId && trailing) {
timeoutId = setTimeout(() => {
lastCall = !leading ? 0 : Date.now();
timeoutId = null;
func.apply(context, args);
}, remaining);
}
};
}
使用示例
// 基础用法
window.addEventListener('resize', throttle(() => {
console.log('窗口大小改变');
}, 200));
// 带选项用法
window.addEventListener('scroll', throttle(() => {
console.log('滚动事件');
}, 100, { leading: false, trailing: true }));
实现要点
- 时间戳方式确保首次触发立即执行
- 定时器方式确保最后一次触发被执行
- 选项参数控制是否立即执行和是否执行尾调用
- 清除多余定时器避免内存泄漏
- 保持正确的函数上下文和参数传递
注意事项
- 节流时间间隔需根据实际场景调整
- 避免在节流函数中执行耗时操作
- 组件卸载时需要移除事件监听器
- 对于动画场景,requestAnimationFrame 可能是更好的选择







