You type "soup" into a search box. Four letters, four requests to the server, and the results of the first three are thrown away at once because you weren't done typing. On a phone with a so-so signal, those requests also fight each other for the connection.
Events such as input, scroll and resize can fire dozens of times a second. If every event starts heavy work right away, such as a request to the server, the page gets sluggish and the server gets flooded. Debounce and throttle are two ways to limit how often a function actually runs. Picture a lift door: it only closes after 3 seconds with nobody stepping in, and every person who steps in starts the count again. That is debounce. Now picture a water dispenser that gives one cup every 3 seconds, however many times you press its button. That is throttle.
Debounce: wait until it stops
Debounce delays a function until the events stop for delay ms. Every new call cancels the old schedule and sets a new one.
| Time | You type | What happens |
|---|---|---|
| 0 ms | s | schedule set: run at 300 ms |
| 100 ms | so | old schedule cancelled, new one: 400 ms |
| 200 ms | sou | cancelled again, new one: 500 ms |
| 300 ms | soup | cancelled again, new one: 600 ms |
| 600 ms | (quiet) | search("soup") runs, the request is sent |
Four keystrokes, 1 request, with the last word.
function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer); // cancel the previous schedule
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const search = debounce((word) => {
console.log("fetch /api/search?q=" + word);
}, 300);
search("s");
search("so");
search("sou");
search("soup");
// 300 ms after the last call, only once:
// fetch /api/search?q=soup
debouncereturns a new function, the wrapper. What you call on every event is this wrapper, notfnitself.let timerlives in the closure, so every call of the wrapper uses the sametimer....argscollects every argument of the call into an array.clearTimeout(timer)cancels the schedule that has not run yet. Iftimeris stillnull, nothing happens.setTimeout(..., delay)sets a new schedule and keeps its number intimer.fn.apply(this, args)calls the original function with thethisand the arguments of the last call.
Three things must hold: before delay has passed, fn has not run at all; three calls in a row give only one run; and after it runs, the wrapper can be used again for the next wave.
Debounce doesn't control the order of the replies. Say you pause for a moment after "soup", its request goes out, but the server is slow. Then you type "soup recipe", and the reply for "soup recipe" arrives first. The late "soup" reply then replaces it, so the wrong results show. The fix: cancel the old request with an AbortController before sending the new one.
let controller = null; // the AbortController of the latest request
async function search(word) {
controller?.abort(); // cancel the previous request if it has not finished
controller = new AbortController();
try {
const res = await fetch("/api/search?q=" + word, { signal: controller.signal });
show(await res.json());
} catch (err) {
if (err.name !== "AbortError") throw err; // cancelled on purpose, not an error
}
}
const searchDebounced = debounce(search, 300);
show is your own function that draws the results on the page. In Chromium 156, with a 900 ms reply for "soup" and a 100 ms reply for "soup recipe", this code shows only the "soup recipe" results. Without the abort() line, the "soup recipe" results show and are then replaced by the "soup" results.
Throttle: at most once per interval
Throttle runs a function at most once every interval ms, for as long as the events keep coming. The events in between are dropped.
function throttle(fn, interval) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
window.addEventListener("scroll", throttle(() => {
console.log("position", window.scrollY);
}, 300));
lastkeeps whenfnlast ran. It starts at0, so the first event runs at once.- If
intervalhas passed since the last run,fnruns and the time is noted. If not, the event is skipped.
Scrolling for 1 second fires an event roughly every 16 ms, about 60 events. With a 300 ms throttle, the handler runs at 0, 304, 608 and 912 ms: 4 times, and it keeps running regularly while the scroll goes on. A 300 ms debounce in the same situation runs once, 300 ms after the scroll stops.
Leading and trailing edge
The edge is when the function runs within one burst of events: at the start (leading) or at the end (trailing).
- The debounce above is trailing: it runs at the end, once things are quiet. A leading version runs on the first event, then ignores the rest until it has been quiet for
delay. That suits a button that must not be sent twice. - The throttle above is leading: the first event runs at once. Its weak spot is that the last position can be lost. In the example, every event after 912 ms is dropped. A throttle with a trailing edge adds one last call with the newest value at 1,212 ms, one interval after the last call.
Libraries such as Lodash have { leading, trailing } options for both.
Which one to pick
| Situation | Pick | Why |
|---|---|---|
| Search box with a request to the server | debounce | the result for the last word is enough |
| Auto-saving a draft | debounce | save once the person stops typing |
| A scroll that calls an API while scrolling | throttle | needs regular updates while moving |
| Resizing the window, then redoing the layout | debounce | once, after it is done, is enough |
| Pointer position while dragging | throttle | has to keep following the movement |
The rule of thumb: debounce waits for the activity to stop, throttle limits how often it runs per interval.
⚠️ Why does every keystroke still send a request?
- Making a new debounce on every event.
input.oninput = (e) => debounce(search, 300)(e.target.value)makes a new wrapper and a newtimerfor every keystroke, so nothing is ever cancelled. Calldebounceonce, keep the result, and call that result on every event. - Forgetting
clearTimeout. Every call is only delayed and none is cancelled, so 4 keystrokes still make 4 requests. The exercise also checks thatclearTimeoutis in your code. - Running
fnstraight away. Iffnis called inside the wrapper beforesetTimeout, it runs on every keystroke. The function may only run from insidesetTimeout. - Losing the arguments.
setTimeout(fn, delay)callsfn()without the search word. Passargson withfn.apply(this, args)orfn(...args).
TL;DR: Debounce delays a function until the events stop for delay ms: every call runs clearTimeout(timer) and then timer = setTimeout(() => fn.apply(this, args), delay), so only the last call runs, with its arguments ("soup" typed in 4 letters, 1 request). Throttle runs a function at most once per interval while the events keep coming (1 second of scrolling with a 300 ms throttle runs 4 times). Leading means running at the start of a burst, trailing at its end. Use debounce for search, drafts and resize. Use throttle for scroll and drag that need updates while moving.
⚡ Debounce: wait until it stops
Write:
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
Guess first: you type "soup" into a search box with a 300 ms debounce. How many requests go out?
One, with the last word. Every keystroke cancels the old schedule with clearTimeout, and only 300 ms after the last keystroke does search("soup") run.
Meaning: debounce returns a wrapper. Call debounce once, keep the result, and call that result on every event.
⚡ Throttle: at most once per interval
Meaning: Throttle runs a function at most once every interval ms while the events keep coming. One second of scrolling with a 300 ms throttle runs 4 times, regularly, while the scroll goes on.
⚡ Which one to pick
Meaning: Debounce waits for the activity to stop, throttle limits how often it runs per interval. Search, drafts and resize get debounce. Scroll and drag that need updates while moving get throttle.