Throttle a function
Run a function at most once every N milliseconds, for example while the user scrolls. (Debounce waits until the user stops; throttle runs regularly.)
JavaScript · Throttle a functionIntermediate
function throttle(fn, wait = 100) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
window.addEventListener('scroll', throttle(() => {
console.log('scrolled to', window.scrollY);
}, 200), { passive: true });throttlescrollperformance