Find the bug · #66 · Caching and state Hard JavaScript
Search fires on every keystroke
A debounced search box still sends a request for every letter typed.
On this page
The report
The search box is debounced, so it should only search once the user stops typing. The API logs show one request per keystroke anyway, and the search service is falling over at peak hours.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Waits until the user stops typing for `ms` before calling fn.
function debounce(fn, ms) {
return (...args) => {
let timer;
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}Read it, then pick a line.
Each call clears timer. Which timer is that?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const calls = [];
const search = debounce((q) => calls.push(q), 30);
for (const q of ['p', 'ph', 'pho', 'phone']) search(q);
await new Promise((r) => setTimeout(r, 80));
console.log(calls.length + ' search(es): ' + calls.join(', '));It prints
4 search(es): p, ph, pho, phone
It should print
1 search(es): phone
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 declares timer inside the returned function, so every keystroke gets a brand-new, empty timer. clearTimeout(timer) clears nothing, and the previous keystroke’s timer still fires. The timer has to live outside, in the closure, so each call can cancel the last one.
The fix
1// Waits until the user stops typing for `ms` before calling fn.2function debounce(fn, ms) {3 let timer;3 return (...args) => {4 let timer;5 clearTimeout(timer);6 timer = setTimeout(() => fn(...args), ms);7 };How you’d find it
- Reproduce: four quick keystrokes, wait, count the searches: four.
- So the earlier timers aren’t cancelled. Log
timerjust beforeclearTimeout: it’s alwaysundefined. - A fresh variable on every call can’t remember the previous call’s timer. Move it up a level.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
const calls = [];
const search = debounce((q) => calls.push(q), 20);
search('a');
search('ab');
await new Promise((r) => setTimeout(r, 60));
assert.deepEqual(calls, ['ab']);Where else this bites
- Throttle functions with the same mistake.
- React: a timer stored in a plain variable inside a component is reset on every render; use
useRef.