js实现节流的方式
使用定时器实现节流
通过定时器控制函数执行频率,确保在指定时间间隔内只执行一次函数调用。
function throttle(func, delay) {
let timer = null;
return function(...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
使用时间戳实现节流
利用时间戳记录上次执行时间,确保当前时间与上次执行时间的间隔大于设定阈值。
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) {
let timer = null;
let lastTime = 0;
return function(...args) {
const now = Date.now();
const remaining = delay - (now - lastTime);
if (remaining <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
func.apply(this, args);
lastTime = now;
} else if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
lastTime = Date.now();
}, remaining);
}
};
}
使用 Lodash 库的节流函数
Lodash 提供了经过优化的节流函数,可直接使用。
import { throttle } from 'lodash';
const throttledFunc = throttle(func, delay);
节流应用示例
将节流应用于滚动事件处理,减少事件触发频率。
window.addEventListener('scroll', throttle(() => {
console.log('Scroll event throttled');
}, 200));






