JavaScriptFundamental (ES6), part 2
Debounce keystrokes and count calls in JavaScript
84 A debounced search box, and how many calls got through
fairWrap a search function so that a burst of keystrokes fires it once, after typing stops, with the last value. Drive it with a clock you control so you can assert exactly how many requests went out and what each one carried. Add a cancel for the component unmounting mid-wait.
Stuck? Three hints, smallest first
- 1. Keep the pending timer id in a closure. Every call clears the previous one before setting a new one.
- 2. Take the clock as an argument —
{ setTimeout, clearTimeout, advance }— so the test never waits. - 3. Hang
canceloff the returned function; it clears the timer and forgets it.
// A clock driven by hand. Nothing here sleeps.
function makeClock() {
let now = 0;
let seq = 0;
const jobs = new Map();
return {
setTimeout(fn, ms) { jobs.set(++seq, { at: now + ms, fn }); return seq; },
clearTimeout(id) { jobs.delete(id); },
advance(ms) {
now += ms;
const due = [...jobs].filter(([, j]) => j.at <= now).sort((a, b) => a[1].at - b[1].at);
for (const [id, job] of due) { jobs.delete(id); job.fn(); }
},
get time() { return now; },
get pending() { return jobs.size; },
};
}
function debounce(fn, wait, clock) {
let timer = null;
const wrapped = (...args) => {
if (timer !== null) clock.clearTimeout(timer);
timer = clock.setTimeout(() => { timer = null; fn(...args); }, wait);
};
wrapped.cancel = () => { if (timer !== null) { clock.clearTimeout(timer); timer = null; } };
return wrapped;
}
const clock = makeClock();
const requests = [];
const search = debounce((q) => requests.push(q), 100, clock);
// Someone types "lag" at 30ms a keystroke.
search('l');
clock.advance(30);
search('la');
clock.advance(30);
search('lag');
clock.advance(30);
const duringTheBurst = requests.length;
clock.advance(100); // typing stopped, the last timer comes due
const afterTheBurst = [...requests];
// A second, separate burst.
search('ikeja');
clock.advance(150);
// And a call abandoned before it could fire.
search('yaba');
search.cancel();
clock.advance(500);
console.log('during the burst :', duringTheBurst, 'requests');
console.log('after it settled :', afterTheBurst);
console.log('in the end :', requests, 'at t =', clock.time + 'ms');
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('three keystrokes in quick succession sent nothing at all', duringTheBurst, 0);
test('once typing stopped, exactly one request went out, carrying the last value', afterTheBurst, ['lag']);
test('a later burst gets its own request', requests, ['lag', 'ikeja']);
test('so five calls produced two requests', requests.length, 2);
test('cancel discards the pending one instead of firing it late', requests.includes('yaba'), false);
test('and leaves no timer behind', clock.pending, 0);
test('all of that happened in 840ms of simulated time and none of real time', clock.time, 840);
The reason to inject the clock is in the assertions: five calls, two requests, and the exact payload of each. With the real setTimeout this exercise could only be watched, and the interesting case — a keystroke arriving 1ms before the timer was due — is not stageable at all.
Debounce and throttle are different promises and the difference matters. Debounce says "run once, after the noise stops", which is what a search box wants; it can wait for ever under continuous input. Throttle says "run at most once per interval", which is what a scroll handler wants. Reaching for the wrong one gives you either a search that never fires or a request per keystroke.
cancel is not a nicety. In a component that unmounts while a debounce is pending, the callback still runs and writes to state that no longer exists, which is the classic "cannot update an unmounted component" warning. The clean-up is one clearTimeout, and the fifth and sixth assertions are what proves it happened.