Sub topic 3
Building a Debounce Function
This chapter assumes you are comfortable with arrow functions, closures, setTimeout and clearTimeout, rest parameters, and addEventListener. The previous chapter covered how closures and timers work. Here you combine them into a working trailing-edge debounce, see why each line is there, and learn the mistakes that quietly break it.
What Debounce Promises
A debounced function delays a call until the calls stop. Each new call cancels the one before it and starts a new countdown. The wrapped function runs only after wait milliseconds pass with no new calls.
This version is called trailing-edge because the work happens at the end of a burst of calls. A search box shows why that matters. If a user types "hello", the input event fires five times. You want one network request for "hello", not five requests for "h", "he", "hel", "hell", and "hello".
The contract has three parts:
- The wrapped function never runs while calls keep arriving less than
waitms apart. - It runs once,
waitms after the last call in a burst. - It receives the arguments from that last call.
The Implementation
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
const input = document.querySelector('#search');
input.addEventListener('input', debounce((event) => {
console.log('Search for:', event.target.value);
}, 300));Each call resets the timer. The wrapped function runs once, 300 ms after the user stops typing, and the arrow function passes on the caller's this and arguments.
Line by Line
| Line | Purpose |
|---|---|
| `let timerId;` | Private state shared by every call to the returned function. Only the closure can reach it. |
| `return function (...args)` | The debounced wrapper. A regular function is used so it receives `this` from whoever calls it. |
| `clearTimeout(timerId);` | Cancels the pending call, if there is one. On the first call `timerId` is `undefined`, and `clearTimeout(undefined)` does nothing. |
| `timerId = setTimeout(...)` | Schedules a new call and stores its ID so the next call can cancel it. |
| `fn.apply(this, args)` | Runs the original function with the wrapper's `this` and the latest arguments. The arrow function does not have its own `this`, so it uses the wrapper's. |
The whole technique depends on timerId living in the closure. It is created once, when debounce runs, and it persists across every call to the wrapper. If it were declared inside the wrapper, each call would get a fresh variable and could never cancel the previous timer.
The next chapter covers this and argument handling in detail. For now, note that args is captured per call. Each new call replaces the scheduled callback, so only the arguments from the final call survive.
Watching It Work
The browser example needs a page. This version runs in Node or a browser console and simulates typing with timers:
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
const start = Date.now();
const search = debounce((query) => {
console.log(`${Date.now() - start}ms: search for "${query}"`);
}, 300);
// First burst: one keystroke every 100 ms
['h', 'he', 'hel', 'hell', 'hello'].forEach((value, i) => {
setTimeout(() => search(value), i * 100);
});
// Second burst after a pause
setTimeout(() => search('hello w'), 1000);
setTimeout(() => search('hello wo'), 1150);Expected output, give or take a few milliseconds:
700ms: search for "hello"
1450ms: search for "hello wo"The last call of the first burst happens at 400 ms, so the search runs at 400 + 300 = 700 ms. The gaps between keystrokes (100 ms) are always shorter than the wait (300 ms), so no earlier timer ever finishes. The second burst works the same way: its last call is at 1150 ms, so the search runs at 1450 ms.
Common Errors
Creating a New Debounced Function on Every Event
This is the most common bug, and it fails without any error message:
// Broken: every event builds a brand-new debounced function
input.addEventListener('input', (event) => {
debounce(runSearch, 300)(event.target.value);
});Each call to debounce creates a new closure with its own timerId. No wrapper ever sees a second call, so nothing gets cancelled. Every keystroke still triggers a search, each one just 300 ms late. Create the debounced function once and reuse it:
const debouncedSearch = debounce(runSearch, 300);
input.addEventListener('input', (event) => {
debouncedSearch(event.target.value);
});The same mistake shows up in component frameworks, where a render function recreates the wrapper. A later chapter covers the React version.
Forgetting clearTimeout
Without the clearTimeout line you get a delay, not a debounce:
// Broken: schedules a call for every input, just later
function delayOnly(fn, wait) {
return function (...args) {
setTimeout(() => fn.apply(this, args), wait);
};
}Five keystrokes still produce five calls. If you test with only a single call, the bug stays hidden because a single call behaves correctly.
Expecting a Return Value
The wrapper returns undefined. The original function runs later, inside a timer callback, after the wrapper has already returned. Nothing can carry its result back to the caller:
const debouncedAdd = debounce((a, b) => a + b, 100);
const result = debouncedAdd(1, 2);
console.log(result); // undefinedIf you need the result, handle it inside fn, for example by updating state or rendering, or design fn to call a callback. A version that returns a Promise is possible, but then every superseded call leaves a Promise that you must either resolve or reject, which complicates callers. Most libraries avoid this. Lodash returns the result of the previous invocation, which is rarely what callers expect.
Passing a Stale Event Object
Debouncing an event handler hands fn the event object from the last call, after a delay. Reading event.target.value later works because it reads the element's current value. But event.preventDefault() does nothing after a delay, because the browser already finished dispatching the event. If you need to prevent a default action, do it in an undebounced handler and debounce only the expensive work:
form.addEventListener('submit', (event) => {
event.preventDefault(); // must run synchronously
debouncedSubmit(new FormData(form));
});Edge Cases Worth Knowing
Choosing wait
The value of wait sets the trade-off between responsiveness and work saved. For search-as-you-type, 200 to 400 ms is typical: fast typists press keys roughly every 100 to 200 ms, so a shorter wait lets requests slip through mid-word. For window resize followed by layout recalculation, 100 to 250 ms is common. For autosave, a second or more is fine.
wait of 0
debounce(fn, 0) still debounces, with a short window. Calls made in the same synchronous block collapse into one, because none of the timers can fire until the current task finishes:
const log = debounce((n) => console.log('ran with', n), 0);
log(1);
log(2);
log(3);
// later: "ran with 3"This is sometimes used to batch several synchronous updates into one piece of work. Calls in separate tasks, such as separate events, are not merged.
Timer Precision
setTimeout guarantees a minimum delay, not an exact one. The callback runs when the event loop gets to it, so a busy main thread pushes it later. Browsers also clamp nested timers to at least about 4 ms and slow down timers in background tabs, sometimes to once per second or less. Do not use a debounce where exact timing matters.
Separate State per Wrapper
Every call to debounce creates independent state. Two inputs that each get their own wrapper are debounced separately. That is usually what you want. Two inputs sharing one wrapper would cancel each other's pending calls, so only the last input that changed would be searched:
const nameSearch = debounce(searchNames, 300);
const citySearch = debounce(searchCities, 300);
nameInput.addEventListener('input', (e) => nameSearch(e.target.value));
cityInput.addEventListener('input', (e) => citySearch(e.target.value));Out-of-Order Responses
Debouncing reduces the number of requests but does not guarantee their order. If the search for "hel" fires, the user resumes typing, and the search for "hello" fires next, the slower response can still arrive last and overwrite the newer results. Debounce is not a fix for this. Track the latest request or cancel the old one with an AbortController:
let controller;
const debouncedFetch = debounce(async (query) => {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
render(await res.json());
} catch (err) {
if (err.name !== 'AbortError') throw err;
}
}, 300);What This Version Does Not Do
This implementation runs only on the trailing edge. It cannot cancel a pending call, run one immediately, or cap the total delay. Later chapters add each of those: leading-edge behavior, cancel and flush, and maxWait. The core stays the same throughout: one closure variable holding one timer, cleared and reset on every call.
Exercise
Calls to a debounced function with wait = 250 happen at 0 ms, 200 ms, 400 ms, and 700 ms, with arguments "a", "b", "c", and "d". When does the wrapped function run, and with which arguments?
Show answer
It runs twice. The gaps 0→200 and 200→400 are under 250 ms, so the timers set at 0 and 200 are cancelled. The timer set at 400 ms would fire at 650 ms, and 650 comes before the next call at 700, so the function runs at 650 ms with "c". The call at 700 ms starts a new timer, and the function runs again at 950 ms with "d".
Exercise
A teammate writes window.addEventListener('resize', () => debounce(updateLayout, 200)()); and says the debounce "doesn't work." Explain what happens and fix it.
Show answer
Each resize event calls debounce again, which creates a new closure with its own timerId. No timer is ever cleared, so updateLayout runs once per resize event, each 200 ms late. The fix is to create the wrapper once: const debouncedLayout = debounce(updateLayout, 200); window.addEventListener('resize', debouncedLayout);.
Exercise
Why does const total = debounce((a, b) => a + b, 100)(2, 3); leave total as undefined, and how should code that needs the sum be structured?
Show answer
The wrapper schedules fn with setTimeout and returns immediately without a return statement, so it returns undefined. The sum is computed later inside the timer callback, after the caller has moved on. Put the code that uses the result inside fn, for example debounce((a, b) => showTotal(a + b), 100), or pass a callback that receives the result.