js throttle实现
函数节流(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;
}
};
}
包含首次和末次调用的版本
支持配置是否立即执行首次调用和是否执行延迟期间的最后一次调用:
function throttle(func, delay, options = {}) {
let lastTime = 0, timer = null;
const { leading = true, trailing = true } = options;
return function(...args) {
const now = Date.now();
const context = this;
if (!lastTime && !leading) lastTime = now;
const remaining = delay - (now - lastTime);
if (remaining <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
func.apply(context, args);
lastTime = now;
} else if (!timer && trailing) {
timer = setTimeout(() => {
func.apply(context, args);
lastTime = leading ? Date.now() : 0;
timer = null;
}, remaining);
}
};
}
使用示例
const throttledScroll = throttle(() => {
console.log('Scroll event handled');
}, 200);
window.addEventListener('scroll', throttledScroll);
实现要点说明
- 时间戳方式保证精确的时间间隔控制
- 定时器方式确保最后一次调用能被执行
- 配置参数提供灵活性:
leading控制首次立即执行,trailing控制末次延迟执行 - 清除定时器避免内存泄漏
- 保持正确的
this上下文和参数传递
实际应用场景
- 页面滚动加载更多内容
- 窗口大小调整时的布局计算
- 按钮频繁点击的防重复提交
- 鼠标移动事件的高频触发控制
这种实现方式比简单使用定时器更精确,能保证函数在指定时间间隔内有规律地执行,同时兼顾首次和末次调用的需求。






