Concept Explanation
Some events fire absurdly often. A scroll handler can run dozens of times a second. A keyup handler on a search box runs once per keystroke, which means a user typing "javascript tutorial" just asked your API nineteen questions and only cared about the last one.
Debounce and throttle both fix this, and they are constantly confused, so anchor them with two images:
Debounce is an elevator door. Every new person walking in resets the timer. The doors only close once nobody has arrived for a few seconds. You get exactly one departure at the end of the burst.
Throttle is a metronome. It fires on a fixed beat and ignores everything in between. During a five-second scroll you get one call every 100ms, steadily, not one call at the end.
The choice follows from the question: do you want the final value, or do you want regular updates along the way?
Syntax or Core Structure
Debounce
function debounce(fn, delay = 300) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const search = debounce((q) => fetch('/api/search?q=' + q), 300);
input.addEventListener('input', (e) => search(e.target.value));
Throttle
function throttle(fn, limit = 100) {
let waiting = false;
let lastArgs = null;
return function (...args) {
if (waiting) { lastArgs = args; return; }
fn.apply(this, args);
waiting = true;
setTimeout(() => {
waiting = false;
if (lastArgs) { fn.apply(this, lastArgs); lastArgs = null; }
}, limit);
};
}
window.addEventListener('scroll', throttle(updateStickyNav, 100));
Cancellable debounce
function debounce(fn, delay = 300) {
let timer;
const wrapped = (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
wrapped.cancel = () => clearTimeout(timer);
return wrapped;
}
Which One, When
| Situation | Use | Why |
|---|---|---|
| Search-as-you-type | Debounce | Only the final query matters |
| Auto-save a draft | Debounce | Save when they pause, not per character |
| Validating a field on blur-ish input | Debounce | Do not shout at a half-typed email |
| Scroll position / sticky header | Throttle | You need steady updates during the scroll |
| Window resize re-layout | Throttle, then a trailing debounce | Smooth during, correct at the end |
| Rate-limiting an analytics ping | Throttle | Predictable ceiling on call volume |
| Animating with scroll position | requestAnimationFrame | Aligns with the frame, better than either |
Real World Example
An autocomplete that cost real money. A team shipped search-as-you-type straight onto input with no limiter. Each keystroke hit a paid geocoding API. Traffic looked fine in testing, then the bill arrived: average query length was around fourteen characters, so they were paying fourteen times per search. Adding a 300ms debounce cut API calls by roughly 90% and made the UI feel better, because results stopped flickering and being replaced mid-read.
Common Mistakes
- Creating the debounced function inside the handler.
onInput={debounce(fn, 300)}in a React render makes a brand-new timer on every keystroke, so nothing is ever debounced. Create it once withuseMemoor outside the component. - Debouncing something that needs to feel instant. A debounced button click looks like a broken button.
- Throttling with a long interval and no trailing call. The final scroll position never arrives and your header sticks in the wrong state.
- Losing
this. Usefn.apply(this, args)or arrow functions consistently, or method calls break. - Not cancelling on unmount. A pending timer fires against a component that no longer exists.
- Debouncing instead of cancelling in-flight requests. Debounce reduces requests; it does not stop an old slow response from overwriting a newer fast one. Use
AbortControllerfor that.
Best Practices
- Pick delays from behaviour, not taste: 250-400ms for typing, 100-150ms for scroll, and
requestAnimationFramefor anything that touches layout. - Expose a
cancelmethod and call it in your cleanup path. - Combine debounce with
AbortControllerfor search: fewer requests and no out-of-order results. - Prefer
IntersectionObserverandResizeObserverover throttled scroll and resize handlers. The platform already solved those cases more efficiently. - Reach for lodash's
debounce/throttlein production; they handle leading and trailing edges,maxWait, and cancellation properly.
Practice Exercises
- The Debouncer: Build a
debouncefunction from scratch that waits 300ms before running, then add acancelmethod and prove it works. - The Counter Comparison: Attach a debounced and a throttled handler to the same
scrollevent, log a counter from each, and scroll for five seconds. Explain the difference in the two totals. - The Race Fix: Build a debounced search where a slow earlier response could overwrite a fast later one, reproduce the bug, then fix it with
AbortController.