Sub topic 6
Debounce or Throttle? Picking the Right Tool
This chapter assumes you have already built the trailing-edge debounce and the timestamp-based throttle from the previous chapters. You should also be comfortable with closures, setTimeout, and the way fn.apply(this, args) passes along context and arguments. Here we stop writing new wrappers and look at how to choose between them. Choosing wrong rarely throws an error. Usually the interface just feels slow or jumpy, or it sends more network requests than it needs to.
The Core Difference in One Sentence Each
- Debounce waits for the events to stop. The handler runs once,
waitmilliseconds after the last event in a burst. - Throttle sets a maximum rate. While events keep arriving, the handler runs at most once every
waitmilliseconds.
Both reduce the number of calls. They differ in when the calls happen. Debounce trades responsiveness for a single, final result. Throttle trades completeness for steady, regular updates.
Seeing Both on the Same Event Stream
The quickest way to build intuition is to feed the same burst of events into both wrappers and compare the output. The script below runs in Node.js or a browser console. It simulates an event every 50 ms for one second, which is roughly what a fast typist or a slow scroll produces.
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 report = (label) => (value) => {
console.log(`${label.padEnd(8)} ran at ~${Date.now() - start} ms with event #${value}`);
};
const debounced = debounce(report('debounce'), 200);
const throttled = throttle(report('throttle'), 200);
let count = 0;
const intervalId = setInterval(() => {
count += 1;
debounced(count);
throttled(count);
if (count === 20) {
clearInterval(intervalId);
}
}, 50);The output looks roughly like this. Exact milliseconds vary because timers are not precise:
throttle ran at ~50 ms with event #1
throttle ran at ~250 ms with event #5
throttle ran at ~450 ms with event #9
throttle ran at ~650 ms with event #13
throttle ran at ~850 ms with event #17
debounce ran at ~1200 ms with event #20Twenty events produced five throttled calls spread across the burst and one debounced call after it. Two details matter for the decision:
- The debounced handler saw only event #20. It never saw any of the intermediate values, and it ran 200 ms after the user stopped.
- The throttled handler never saw event #20. The simple timestamp throttle drops whatever arrives inside the cooldown window, including the last event. If the final state matters, you need the trailing-call version covered in a later chapter.
The Questions That Decide It
Ask these questions in order. The first one that gets a clear answer usually settles the choice.
1. Does the user need feedback while the events are still happening?
If the user is dragging, scrolling, or resizing and expects the screen to respond continuously, debounce is the wrong tool. A debounced scroll handler that updates a progress bar would leave the bar frozen until scrolling stops, then make it jump. Use throttle, or requestAnimationFrame if the work is purely visual.
2. Does only the final value matter?
A search box needs results for what the user ended up typing, not for every intermediate prefix. Sending a request for "r", "re", "rea", and "reac" wastes bandwidth and can produce out-of-order responses. Debounce fits because it delivers exactly the final value.
3. How expensive is each call?
Cheap work, such as reading window.scrollY and toggling a class, can tolerate a throttle at 100 ms or even per frame. Expensive work like a network request, a full layout recalculation, or writing to storage should run as rarely as possible. That pushes you toward debounce, or toward a long throttle interval.
4. Can the burst go on indefinitely?
Debounce has a failure mode called starvation. If events never pause for wait milliseconds, the handler never runs. A user who types continuously into an autosaving editor for two minutes would lose two minutes of work if the browser crashed. When bursts can be long and you still want debounce semantics, add a maxWait bound. A later chapter covers it.
Common Events and Sensible Defaults
The table gives starting points, not rules. Measure in your own app before settling on numbers.
| Scenario | Event | Technique | Typical wait | Reason |
|---|---|---|---|---|
| Search-as-you-type | `input` | Trailing debounce | 250–400 ms | Only the final query matters, and requests are expensive |
| Form field validation | `input` | Trailing debounce | 300–500 ms | Showing errors mid-word is distracting |
| Autosave a draft | `input` | Debounce with `maxWait` | 1000 ms, max 5000 ms | Save after a pause, but never go too long without saving |
| Recompute layout after resize | `resize` | Trailing debounce | 150–250 ms | The final size is what counts |
| Sticky header or scroll spy | `scroll` | Throttle with trailing call | 100–200 ms | Needs continuous feedback and the correct final position |
| Infinite scroll trigger | `scroll` | Throttle | 200–300 ms | Check regularly while scrolling and stay cheap |
| Drag or follow the cursor | `pointermove` | `requestAnimationFrame` | One frame | Updates match the display refresh rate |
| Prevent double-submit | `click` | Leading-edge debounce | 500–1000 ms | Respond instantly and ignore repeat clicks |
| Analytics for mouse movement | `pointermove` | Throttle | 500–1000 ms | Sampling is enough, and every call costs bandwidth |
| Calling a rate-limited API | Any | Throttle | Matches the API limit | Guarantees you never exceed N calls per period |
Choosing the Wait Value
The wait value matters as much as the technique.
- Under 100 ms feels instantaneous to most users. Shorter waits cost more calls but add no visible lag.
- 100–300 ms is the typical range for typing pauses. Typists often leave 100–200 ms between keystrokes, so a debounce shorter than about 150 ms can fire mid-word.
- Over 500 ms begins to feel sluggish for anything the user is waiting to see. Reserve it for background work such as saving and analytics.
- About 16 ms corresponds to one frame at 60 Hz. If you find yourself writing
throttle(fn, 16), userequestAnimationFrameinstead. It adapts to 120 Hz displays and pauses in background tabs.
Failure Modes of the Wrong Choice
| Mistake | Symptom | Fix |
|---|---|---|
| Debouncing a continuous visual update | UI freezes during the gesture, then jumps | Throttle or use `requestAnimationFrame` |
| Throttling a search box | Requests for partial words and stale results | Debounce on `input` |
| Timestamp throttle on scroll position | Final position wrong after a fast flick | Throttle with a trailing call |
| Debounce on endless input | Handler never runs, so work is never saved | Add `maxWait` |
| Trailing debounce on a submit button | First click feels ignored for `wait` ms | Leading-edge debounce |
| Wait value too short | Little or no reduction in calls | Measure the real event rate and raise `wait` |
A Note on Combining Them
Debounce and throttle are two settings of the same mechanism. A debounce with maxWait equal to wait behaves like a throttle with leading and trailing calls. Lodash's throttle is in fact implemented by calling its debounce with maxWait set to wait. Keep this in mind when reading library options. The difference is whether a guaranteed maximum interval applies, plus which edges fire.
Exercises
Exercise
A map app redraws visible markers when the user pans by dragging. Redrawing takes about 5 ms. Should you debounce or throttle the pointermove handler, and with what mechanism?
Show answer
Throttle it, because the user needs continuous feedback during the drag. Redrawing is visual work, so requestAnimationFrame is the best fit. It runs the redraw once per frame with the latest pointer position, and at 5 ms per redraw it fits within a 16 ms frame budget.
Exercise
In the comparison script, the throttled handler never received event #20. Explain why, and name a scenario where that loss would be a visible bug.
Show answer
Event #20 arrived at about 1000 ms, only about 150 ms after the last throttled call at about 850 ms. That is inside the 200 ms cooldown, so the timestamp throttle dropped it, and no later event arrived to trigger another call. A scroll-spy navigation that highlights the current section would show the wrong section after a quick scroll, because the final scroll position was never processed.
Exercise
A note-taking app debounces saving by 1000 ms. Users report losing work after typing nonstop for several minutes before a crash. What is the cause and the fix?
Show answer
The cause is debounce starvation. Continuous typing never leaves a 1000 ms pause, so the trailing call keeps getting postponed and the save never runs. The fix is to add a maxWait bound, for example 5000 ms, so a save is forced at least that often during a long burst. You can also flush the pending save on beforeunload or visibilitychange.