01
Implement a throttle function.
Show answer
Throttle allows a function to run at most once in a given interval:
function throttle(fn, wait) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
window.addEventListener('scroll', throttle(updateProgressBar, 100));
Unlike debounce, which waits for calls to stop, throttle fires regularly during continuous events such as scrolling or dragging.