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);
};
}
包含首次和末次执行的版本
function throttle(func, delay, options = {}) {
let lastCall = 0;
let timer = null;
const { leading = true, trailing = true } = options;
return function(...args) {
const now = new Date().getTime();
const remaining = delay - (now - lastCall);
if (remaining <= 0 && leading) {
lastCall = now;
func.apply(this, args);
} else if (trailing && !timer) {
timer = setTimeout(() => {
lastCall = new Date().getTime();
timer = null;
func.apply(this, args);
}, remaining);
}
};
}
使用场景示例
滚动事件节流处理:
const handleScroll = throttle(() => {
console.log('处理滚动事件');
}, 200);
window.addEventListener('scroll', handleScroll);
实现注意事项
- 确保正确绑定函数上下文(this)
- 考虑边界情况(如delay为0或负数)
- 清除未执行的定时器避免内存泄漏
- 支持立即执行和延迟执行选项
现代实现方案
使用requestAnimationFrame的节流版本:

function rafThrottle(func) {
let ticking = false;
return function(...args) {
if (!ticking) {
requestAnimationFrame(() => {
func.apply(this, args);
ticking = false;
});
ticking = true;
}
};
}
性能优化建议
- 对于动画相关场景,优先使用requestAnimationFrame
- 避免在节流函数内执行耗时操作
- 根据实际需求调整节流时间间隔
- 考虑使用lodash等库的成熟实现






