用javascript写一个完备版节流函数
以下是一个完备版的节流函数:
function throttle(fn, delay) {
let lastCallTime, timeoutId;
return function(...args) {
const now = Date.now();
if (lastCallTime && now < lastCallTime + delay) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
lastCallTime = now;
fn.apply(this, args);
}, delay);
} else {
lastCallTime = now;
fn.apply(this, args);
}
}
}
使用示例:
function handleScroll() {
console.log('scroll event handled');
}
const throttledHandleScroll = throttle(handleScroll, 1000);
window.addEventListener('scroll', throttledHandleScroll);
上述代码中,throttle 函数接收两个参数:要节流的函数 fn 和节流延迟时间 delay,并返回一个新的函数。
每当新的 fn 被调用时,throttle 函数会记录当前时间 now。如果上一次调用 fn 的时间和 now 的时间差小于 delay,则会清除上一个定时器并再次设置一个新的定时器,以延迟调用 fn 函数。否则,直接调用 fn 函数。
这样做可以确保 fn 函数最多每隔 delay 毫秒被调用一次,以避免在高频事件中频繁执行代码导致的性能问题。
原文地址: http://www.cveoy.top/t/topic/tJL 著作权归作者所有。请勿转载和采集!