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选项的实现
更完善的实现通常提供两个选项:

- leading:是否立即执行第一次调用
- trailing:是否在时间间隔结束后执行最后一次调用
function throttle(func, wait, options = {}) {
let timeout, context, args, result;
let previous = 0;
const later = function() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
const throttled = function(...params) {
const now = Date.now();
if (!previous && options.leading === false) previous = now;
const remaining = wait - (now - previous);
context = this;
args = params;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
throttled.cancel = function() {
clearTimeout(timeout);
previous = 0;
timeout = context = args = null;
};
return throttled;
}
使用示例
// 基础用法
const throttledScroll = throttle(() => {
console.log('Scroll event handler');
}, 200);
window.addEventListener('scroll', throttledScroll);
// 带选项的用法
const throttledResize = throttle(() => {
console.log('Resize event handler');
}, 500, { leading: true, trailing: true });
window.addEventListener('resize', throttledResize);
注意事项
- 时间间隔参数应根据实际需求调整,过短可能达不到节流效果,过长会影响用户体验
- 在组件卸载时应取消节流函数,避免内存泄漏
- 对于React组件,可在useEffect中返回取消函数
useEffect(() => {
const throttledHandler = throttle(handler, 300);
window.addEventListener('resize', throttledHandler);
return () => {
throttledHandler.cancel();
window.removeEventListener('resize', throttledHandler);
};
}, [handler]);






