Throttling is similar to debouncing but solves a different problem: instead of waiting for calls to stop, a throttled function guarantees it runs at most once every fixed interval, no matter how many times it’s triggered in between. This is the right tool for continuous, high-frequency events like scroll or mousemove, where you still want regular updates — just not on every single event.
JavaScript Program to Throttle a Function
function throttle(fn, interval) {
let lastRun = 0;
return function (...args) {
const now = Date.now();
if (now - lastRun >= interval) {
lastRun = now;
fn.apply(this, args);
}
};
}
function onScroll(callNumber) {
console.log(`Scroll handler executed on call #${callNumber}`);
}
const throttledScroll = throttle(onScroll, 1000);
// Simulate 6 scroll events fired 200ms apart (1.2 seconds total)
for (let i = 1; i <= 6; i++) {
setTimeout(() => throttledScroll(i), i * 200);
}
Output:
Scroll handler executed on call #1
Scroll handler executed on call #6
Even though throttledScroll() is called six times over 1.2 seconds, the lastRun timestamp check lets only two of those calls through: the first one fires immediately (since lastRun starts at 0), and the next one to get through is the sixth, once a full 1000ms has elapsed since the last successful run. Debounce and throttle solve similar-looking problems with opposite guarantees — debounce waits for quiet, throttle enforces a steady maximum rate.
