Sub topic 3
Building a Debounce Function
This chapter assumes you know closures, setTimeout and clearTimeout, and how to attach a DOM event listener. You will build a trailing-edge debounce. That is a wrapper that waits until calls stop arriving, then runs the wrapped function once.
The Idea in One Sentence
Each call cancels the pending timer and starts a new one, so the function runs only after wait milliseconds pass with no new calls.
Picture a user typing "cat" into a search box. Each keystroke fires an input event. You do not want three network requests. You want one, after the user pauses.
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));Here is what each part does:
let timerIdlives in the closure. Every call to the returned function sees the same variable, and that shared variable is what lets one call cancel another call's timer.clearTimeout(timerId)cancels the previous pending run. On the first calltimerIdisundefined, andclearTimeout(undefined)does nothing, so no special case is needed.setTimeout(...)schedules a fresh run and stores the new ID....argscollects whatever arguments the caller passed, here the event object, so the handler receives them later.
The returned function is a regular function, and the timer callback is an arrow function, so the arrow picks up the this of the call. The next chapter explains why that matters.
Trying It Without a Browser
You can check the behavior in Node:
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
const log = debounce((msg) => console.log('Ran with:', msg), 100);
log('a');
log('b');
setTimeout(() => log('c'), 50); // still inside the window
setTimeout(() => log('d'), 300); // after a quiet gap
// Output:
// Ran with: c
// Ran with: dCalls a, b, and c land within 100 ms of each other, so only c runs. The d call comes after a gap, so it starts a new burst and runs on its own.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `debounce(...)` inside the event handler | Every event gets its own new timer, so nothing is debounced | Create the debounced function once and pass it to `addEventListener` |
| Declaring `timerId` inside the returned function | Each call has its own variable, so `clearTimeout` never cancels anything | Keep `timerId` in the outer function's scope |
| Forgetting `clearTimeout` | The handler runs once per call, only delayed | Clear before scheduling |
| Expecting a return value | The debounced function returns `undefined` | Handle results inside `fn`, or use callbacks or promises |
Exercise
A debounced function with wait 200 ms is called at t = 0, 150, 300, and 600 ms. At what times does the wrapped function actually run, and with which call's arguments?
Show answer
It runs at t = 500 ms with the arguments from the t = 300 call, because the calls at 0, 150, and 300 are each under 200 ms apart, so each resets the timer, and the last reset expires at 300 + 200. It runs again at t = 800 ms with the arguments from the t = 600 call, which came after a quiet gap and started a new burst.
Exercise
A developer writes input.addEventListener('input', (e) => debounce(search, 300)(e)). Why does search run on every keystroke?
Show answer
Each event creates a new debounced wrapper with its own timerId closure, so no later call can clear an earlier timer. Create the wrapper once, outside the listener, and pass that same function as the handler.