问题:限制频繁触发的事件(如滚动或调整大小)的函数执行速率。
解决方案:使用节流阀函数来限制函数的执行速率。
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function (...args) {
if (!lastRan) {
func.apply(this, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if (Date.now() - lastRan >= limit) {
func.apply(this, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
window.addEventListener(
"scroll",
throttle(() => {
console.log("Window scrolled");
}, 500),
);