Debounce and Throttle
Debounce waits until events stop arriving, then runs once. Throttle runs at most once per interval while events keep arriving. Both turn a noisy event stream into a cheaper one.
Detailed Explanation
A text box input event can fire on every key. A resize handler can fire every frame. A scroll handler can fire dozens of times a second. Doing heavy work (filter a 10k-row list, hit an API, measure layout) on each event janks the page or floods the server.
Debounce restarts a timer on every event. Only the last event in a burst, after a quiet period, runs the function. Search-as-you-type is debounce: you want the query after the user pauses, not after every letter. Leading-edge debounce runs immediately then ignores until quiet; trailing-edge (the usual) waits for quiet.
Throttle guarantees a maximum rate. The first event in a window runs, then further events are ignored until the window ends (leading). Or you run at the end of each window with the latest args (trailing). Scroll-position updates and "save at most every 2s" are throttle.
Neither is in the language. You write a closure over setTimeout / clearTimeout, or you use a utility. The wrapper must decide what this and arguments mean: typically the last call's. Cancel is a method on the wrapper (debounced.cancel()) so unmounting a component does not fire after teardown.
requestAnimationFrame is a cousin for visual work: at most once per frame, aligned to paint. Use it for animation and scroll-linked drawing, not for network calls.
What it costs you: delayed feedback and stale closures. A debounce of 300 ms feels laggy if you also disable the button. A throttle that captured items from the first render will filter old data unless the wrapped function reads fresh state or you re-create the wrapper when deps change (and then you must cancel the old one).
Reach for debounce when only the last value matters. Reach for throttle when you need periodic samples during a continuous gesture. Reach for neither when the event is already rare (submit click). Do the heavy work in a worker if even one run is expensive.
Code Examples
function debounce(fn, ms) {
let timer;
function wrapped(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, ms);
}
wrapped.cancel = () => clearTimeout(timer);
return wrapped;
}
const search = debounce((q) => {
console.log("query", q);
}, 200);
search("a");
search("ab");
search("abc");
// after 200 ms quiet: query abcfunction throttle(fn, ms) {
let last = 0;
let timer;
return function wrapped(...args) {
const now = Date.now();
const remaining = ms - (now - last);
if (remaining <= 0) {
clearTimeout(timer);
last = now;
fn.apply(this, args);
} else if (!timer) {
timer = setTimeout(() => {
last = Date.now();
timer = undefined;
fn.apply(this, args);
}, remaining);
}
};
}
const onScroll = throttle(() => {
console.log("scroll", Date.now());
}, 100);Common Gotchas
A debounce timer outlives a UI component
call `cancel` on unmount or the callback runs against a dead view.
Recreating the wrapper every render resets the timer
memoize debounce/throttle, or put it in a ref, and list the real dependencies.
Debounce can starve if events never pause
a held key that repeats forever never goes quiet. Throttle that path, or use a max-wait.
`this` inside the original function depends on how you call the wrapper
use `fn.apply(this, args)` if the callee is a method.