js截流实现
截流(Throttling)的实现方法
截流是一种限制函数调用频率的技术,确保函数在指定时间间隔内最多执行一次。适用于滚动事件、窗口调整等高频触发的场景。
基础实现方案
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
func.apply(this, args);
lastCall = now;
}
};
}
包含尾部调用保证的版本
function throttle(func, delay) {
let timerId;
let lastCall = 0;
return function(...args) {
const now = Date.now();
const remaining = delay - (now - lastCall);
clearTimeout(timerId);
if (remaining <= 0) {
func.apply(this, args);
lastCall = now;
} else {
timerId = setTimeout(() => {
func.apply(this, args);
lastCall = Date.now();
}, remaining);
}
};
}
使用示例
window.addEventListener('scroll', throttle(function() {
console.log('Scroll event handler');
}, 200));
与防抖(Debounce)的区别
截流保证定期执行,而防抖只在停止操作后执行一次。高频事件处理时:
- 截流更适合实时反馈场景
- 防抖更适合最终状态确认场景
现代浏览器原生方案
现代浏览器支持requestAnimationFrame实现更流畅的动画节流:

function rafThrottle(func) {
let ticking = false;
return function(...args) {
if (!ticking) {
requestAnimationFrame(() => {
func.apply(this, args);
ticking = false;
});
ticking = true;
}
};
}
注意事项
- 时间间隔参数需要根据实际场景调整
- 确保清除定时器避免内存泄漏
- 考虑this绑定和参数传递问题
- 移动端可能需要更长的间隔时间
这些实现方案可根据具体需求选择使用,基础版本已能满足多数场景需求,特殊场景可选用尾部调用保证版本或RAF方案。






