Controlling Frequency
Unlike Debounce (which waits for a pause), Throttle ensures a function is called at most once every N milliseconds, regardless of how many times the trigger fires.
The Throttle Principle
When an action fires continuously (like scroll or mousemove), execute the code once per 100ms. All other calls in between are ignored.
function throttle(fn, limitMs) {
let isThrottled = false;
return function(...args) {
if (isThrottled) return; // Still in cooldown? Skip.
fn.apply(this, args); // Execute immediately
isThrottled = true;
setTimeout(() => {
isThrottled = false; // Cooldown finished, ready for next call
}, limitMs);
};
}
// Usage: update scroll position indicator at most 10 times per second
window.addEventListener('scroll', throttle(updateProgressBar, 100));
Debounce vs Throttle: Side-by-Side
| Debounce | Throttle | |
|---|---|---|
| Behavior | Waits for a pause | Fires at a regular interval |
| Best for | Search, autosave, validation | Scroll tracking, resize, games |
| Fires during rapid actions? | No (resets the timer) | Yes (but at most once per interval) |
Tip
Throttle is perfect for: scroll tracking, window resize handling, updating a game character's position on mousemove, and any situation where you need a guaranteed regular " heartbeat " of updates.