Debounce a function in JavaScript
Advanced · 4 min read
Some events fire many times in quick succession. A search box fires on every key press. A window fires on every pixel of a resize. If each one triggers a network request or a save, you do far more work than you need. Debouncing fixes that: wait until the calls stop for a moment, then run once, with the latest value.
In this tutorial you will write debounce(fn, wait), which wraps a function so that a burst of calls only runs it once, after wait milliseconds of quiet. Then you will learn how to test timing code without actually waiting, by passing in a clock you control. You need to know what a function is and that functions can be passed around like values.
setTimeout and clearTimeout
setTimeout(fn, ms) runs fn once, after roughly ms milliseconds. It returns an id. Passing that id to clearTimeout cancels the timer before it fires.
const id = setTimeout(() => console.log('this never prints'), 100);
clearTimeout(id);
setTimeout(() => console.log('this prints after 50ms'), 50);
Those two functions are all the timing a debounce needs.
Closures: functions that remember
A function created inside another function can keep using that outer function's variables, even after the outer function has finished. This is called a closure:
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
Each call to next sees the same count. Debounce uses this to remember the pending timer between calls.
Here is the exercise. Try it yourself first if you like, or follow the steps.
39 Debounce a repeated call
hardWrap a function so that calling it repeatedly in quick succession only runs it once, after things settle. Adapted: uses a controllable clock so the behaviour can be asserted instead of waited for.
Stuck? Three hints, smallest first
- 1. Keep the pending timer id and clear it every time a new call arrives.
- 2. Real code uses
setTimeout. A test needs a clock you control. - 3. Debounce waits for quiet; throttle runs at most once per interval. They are not the same.
Step 1: debounce with the real timers
Every time the wrapped function is called, cancel the timer that is waiting (if any) and start a new one. Only a timer that survives wait milliseconds without being cancelled ever fires.
function debounce(fn, wait) {
let timer = null;
return (...args) => {
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
const save = debounce((value) => console.log('saving', value), 100);
save('a');
save('b');
save('c');
// About 100ms later, one line: saving c
...args collects whatever arguments the caller passed, and fn(...args) passes them on. 'a' and 'b' are cancelled before their timers fire, so only 'c' gets through.
Step 2: the testing problem
That works, but how would you prove it? You would have to wait 100 milliseconds and then check. Waiting makes tests slow, and real timers can run a little late on a busy machine, which makes tests flaky. The standard fix is to stop reaching for the global timers and accept them as an argument. In a test you pass a fake clock. In the app you pass the real one.
Step 3: a clock you drive by hand
A fake clock needs the same two methods, setTimeout and clearTimeout, plus advance(ms) to move time forward on command. It keeps the waiting jobs in a Map from id to { at, fn }, where at is the time the job is due:
function makeClock() {
let now = 0;
let next = 1;
const jobs = new Map();
return {
setTimeout(fn, delay) {
const id = next++;
jobs.set(id, { at: now + delay, fn });
return id;
},
clearTimeout(id) { jobs.delete(id); },
advance(ms) {
now += ms;
for (const [id, job] of [...jobs.entries()]) {
if (job.at <= now) { jobs.delete(id); job.fn(); }
}
},
};
}
const clock = makeClock();
clock.setTimeout(() => console.log('ding'), 50);
clock.advance(49); // nothing yet
clock.advance(1); // ding
Nothing happens on its own. Time only moves when the test calls advance, so the test decides exactly what "now" is.
Step 4: debounce with an injected clock
Change debounce to use whatever clock it is given:
function debounce(fn, wait, clock) {
let timer = null;
return (...args) => {
if (timer !== null) clock.clearTimeout(timer);
timer = clock.setTimeout(() => fn(...args), wait);
};
}
The logic is the same as Step 1. Only setTimeout and clearTimeout have become clock.setTimeout and clock.clearTimeout. Passing in what a function depends on, instead of letting it reach for a global, is called dependency injection.
Step 5: prove it
Now the timing can be checked step by step, with no waiting:
const clock = makeClock();
const calls = [];
const save = debounce((value) => calls.push(value), 100, clock);
save('a');
save('b');
save('c');
console.log(calls.length); // 0: nothing runs straight away
clock.advance(99);
console.log(calls.length); // 0: one millisecond early, still nothing
clock.advance(1);
console.log(calls); // [ 'c' ]: one run, with the last argument
save('d');
clock.advance(100);
console.log(calls); // [ 'c', 'd' ]: a later call runs on its own
Four calls produced exactly two runs, each carrying the latest value. In real code you pass the real timers instead, for example debounce(search, 300, window) in a browser, since window has both methods.
Debounce vs throttle
These two are often confused. Debounce waits for quiet, then runs once. If the calls never stop, it never runs. Throttle runs at most once per interval while the calls keep coming. Use debounce for "search after the user stops typing", and throttle for "update the position while the user scrolls".
The full solution
The complete answer has the hand-driven clock and debounce, makes three rapid calls, and records how many runs there were immediately, 1 millisecond early, after the full wait and after a later call. Press Run to see the output.
// A clock we drive by hand, so the test does not have to wait.
function makeClock() {
let now = 0;
let next = 1;
const jobs = new Map();
return {
setTimeout(fn, delay) {
const id = next++;
jobs.set(id, { at: now + delay, fn });
return id;
},
clearTimeout(id) { jobs.delete(id); },
advance(ms) {
now += ms;
for (const [id, job] of [...jobs.entries()]) {
if (job.at <= now) { jobs.delete(id); job.fn(); }
}
},
};
}
function debounce(fn, wait, clock) {
let timer = null;
return (...args) => {
if (timer !== null) clock.clearTimeout(timer); // cancel the previous one
timer = clock.setTimeout(() => fn(...args), wait);
};
}
const clock = makeClock();
const calls = [];
const save = debounce((value) => calls.push(value), 100, clock);
save('a');
save('b');
save('c'); // only this one should survive
// Snapshots have to be taken at the moment they describe, not at the end.
const immediately = calls.length;
clock.advance(99);
const justBefore = calls.length;
clock.advance(1);
const afterWait = [...calls];
save('d');
clock.advance(100);
console.log('immediately :', immediately);
console.log('after 99ms :', justBefore);
console.log('after the full wait:', afterWait);
console.log('and a later call :', calls);
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('nothing runs immediately', immediately, 0);
test('nothing has run one tick early either', justBefore, 0);
test('one call after the wait, not three', afterWait.length, 1);
test('and it carried the last argument', afterWait[0], 'c');
test('a later call runs separately', calls[1], 'd');
test('exactly two runs came from four calls', calls.length, 2);
test('the real version is this code with the global clock', typeof setTimeout, 'function');
Adapted: the usual version uses the real setTimeout and therefore can only be watched, not asserted. Injecting a clock is the standard fix for testing anything time-based, and it is the whole reason this exercise can prove that three rapid calls produce exactly one run with the last argument. In production you pass the real window timers instead.
Common mistakes
- Creating the timer variable inside the returned function. Each call would get a fresh
timer, so nothing is ever cancelled. It has to live in the outer function. - Forgetting to pass the arguments on.
setTimeout(fn, wait)callsfnwith no arguments, so the latest value is lost. Use() => fn(...args). - Testing timing with real waits. The tests are slow and sometimes fail for no reason. Inject a clock.
Try it yourself
- Add a
cancel()method to the debounced function that clears the pending timer. - Write a "leading" debounce that runs on the first call of a burst and ignores the rest until things go quiet.
- Write
throttle(fn, interval, clock)and test it withmakeClock: calls every 10ms for 100ms with an interval of 50 should run it about twice.