Sub topic 6
Debounce or Throttle? Picking the Right Tool
This chapter assumes you have already built the trailing-edge debounce and timestamp-based throttle functions from the earlier chapters. You should also understand how setTimeout schedules work on the event loop. Here the question is which of the two to use for a given event.
The Core Difference
Both techniques limit how often a handler runs. They differ in what they promise.
- Debounce waits for a pause. The handler runs once, after the events have stopped for
waitmilliseconds. While events keep arriving, nothing runs. - Throttle sets a steady rate. The handler runs at most once every
waitmilliseconds, even while events keep arriving.
So the useful question is whether you care about the result of a burst or about progress during the burst. If you only need the final state, debounce. If the user should see updates while the activity continues, throttle.
Seeing It in Numbers
The script below fires a call every 50 ms for one second, then stops. It runs in Node or a browser console.
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), wait);
};
}
function throttle(fn, wait) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
const start = Date.now();
const log = (label) => (n) =>
console.log(`${label} ran with call #${n} at ${Date.now() - start} ms`);
const d = debounce(log('debounce'), 200);
const t = throttle(log('throttle'), 200);
let n = 0;
const intervalId = setInterval(() => {
n += 1;
d(n);
t(n);
if (n === 20) clearInterval(intervalId);
}, 50);The throttled handler runs about five times during the burst. The calls land roughly 200 ms apart. The debounced handler runs once, at about 1200 ms, with call #20. Twenty events turn into five calls with one technique and one call with the other.
Common Events and Good Defaults
| Event or task | Technique | Why |
|---|---|---|
| Search-as-you-type request | Debounce (250–400 ms) | Only the finished query matters, and fewer requests means less server load |
| Form field validation | Debounce (300–500 ms) | Showing errors in the middle of typing is distracting |
| Autosave a draft | Debounce with `maxWait` | Save after a pause, and still save during long, nonstop typing |
| Window `resize` layout recalculation | Throttle (100–250 ms) | The layout should keep up while the user drags |
| Infinite scroll "near bottom" check | Throttle (100–200 ms) | The check must run while scrolling, before the scrolling stops |
| Dragging or pointer-following visuals | rAF throttle | Updates should match the display's frame rate |
| Analytics for scroll depth | Throttle | You want samples over time, not one final reading |
Common Mistakes
- Debouncing scroll-driven UI. A sticky header or progress bar that only updates after scrolling stops looks laggy. Use throttle.
- Throttling search requests without a trailing call. The basic timestamp throttle can drop the last keystroke, so the results don't match the final query. Debounce instead, or use the trailing throttle covered later.
- Picking
waitby guesswork. Very long debounce waits make an interface feel unresponsive. Very short throttle waits do little to reduce the work. Start from the ranges in the table and measure. - Treating either one as a fix for slow handlers. Rate limiting cuts down how many calls happen. It does not make each call faster. If a single call takes 80 ms, the page will still stutter.
Exercise
A map component fetches nearby points of interest whenever the user pans. Panning fires pointermove dozens of times per second. The map tiles must follow the finger smoothly, and the points-of-interest request is expensive. Which technique fits each part?
Show answer
Move the map tiles with requestAnimationFrame throttling, because they are visual updates that must keep pace with the pointer. Debounce the points-of-interest fetch, because only the final map position matters for the expensive request. Add a maxWait if results should refresh during a long pan.
Exercise
In the simulation above, why does the debounced handler run at about 1200 ms rather than 1000 ms?
Show answer
The last call arrives at about 1000 ms. Each call resets the 200 ms timer, so the handler runs 200 ms after that final call.