js截流怎么实现
实现 JavaScript 截流(Throttling)的方法
截流(Throttling)是一种控制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。以下是几种常见的实现方式:
使用时间戳实现基础截流
通过比较当前时间与上一次执行时间来判断是否执行函数。

function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
func.apply(this, args);
lastCall = now;
}
};
}
使用定时器实现延迟执行
在延迟时间内只设置一次定时器,确保函数在延迟结束后执行。
function throttle(func, delay) {
let timeoutId = null;
return function(...args) {
if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
}, delay);
}
};
}
结合时间戳和定时器的优化版本
首次触发立即执行,后续触发在延迟结束后执行,同时确保最后一次触发被执行。

function throttle(func, delay) {
let lastCall = 0;
let timeoutId = null;
return function(...args) {
const now = new Date().getTime();
const remaining = delay - (now - lastCall);
if (remaining <= 0) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
func.apply(this, args);
lastCall = now;
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
lastCall = new Date().getTime();
}, remaining);
}
};
}
使用 Lodash 库的截流函数
如果项目中已引入 Lodash,可以直接使用其提供的 _.throttle 方法。
const throttledFunc = _.throttle(originalFunc, 300);
实际应用示例
以下是一个滚动事件中使用截流的例子:
window.addEventListener('scroll', throttle(function() {
console.log('Scroll event throttled');
}, 300));
截流技术适用于高频触发的事件(如滚动、窗口调整、鼠标移动等),可以有效减少不必要的计算或请求,提升性能。






