Debounce a search input in JavaScript
Advanced · 5 min read
Type into the search box on a big site and results appear as you go, but not after every single letter. If the page sent a search request for "A", then "Ab", then "Abu", most of that work would be thrown away the moment you typed the next letter. Instead, it waits until you pause, then searches once. That waiting trick is called debouncing.
In this tutorial you will count the events a text box fires as someone types, write a debounce function that waits for a quiet moment before doing the slow work, and connect it to a search box so a whole word triggers one search. You should have used addEventListener and know what an arrow function is.
The input event
A text box fires an input event every time its value changes: each letter typed, each letter deleted, each paste. Typing "Abuja" fires five of them. That's the right event for a search box, and it's also the reason we need debouncing.
<input id="box" placeholder="Type a route">
Timers: setTimeout and clearTimeout
setTimeout(fn, ms) plans to run fn once, ms milliseconds from now, and gives back an id number for that plan. clearTimeout(id) cancels the plan, if it hasn't run yet.
const id = setTimeout(() => console.log('cancelled, never runs'), 100);
clearTimeout(id);
setTimeout(() => console.log('this one runs'), 100); // this one runs
Debouncing is built from just these two functions.
Here is the exercise. Try it yourself first, or read on and we will build it.
15 Debounce a text input
hardWait until typing has stopped before doing expensive work, so a search box does not fire a request per keystroke.
Stuck? Three hints, smallest first
- 1. Keep the timer id and clear it at the start of every call.
- 2. Debounce waits for quiet. Throttle runs at a fixed rate. They are not the same.
- 3. Take the timer functions as arguments so the delay can be tested without waiting.
Step 1: count the keystrokes
const box = document.getElementById('box');
let keystrokes = 0;
box.addEventListener('input', () => keystrokes++);
const type = (text) => {
box.value = text;
box.dispatchEvent(new Event('input'));
};
for (const partial of ['A', 'Ab', 'Abu', 'Abuj', 'Abuja']) type(partial);
console.log(keystrokes); // 5
type fakes one keystroke: it sets the box's value and fires input, the way the browser does when a key is pressed. Five letters, five events. If each one sent a search request, that's five requests for one word.
Step 2: the debounce idea
The plan: on every keystroke, cancel the previous plan and make a new one for 300 milliseconds later. While the person keeps typing, each new keystroke cancels the last plan before it gets to run. Only when they pause for 300 milliseconds does a plan survive, and the search runs once, with the final value.
Step 3: write debounce
function debounce(fn, wait) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
const search = debounce((value) => console.log('search for', value), 300);
search('A');
search('Ab');
search('Abu'); // search for Abu
debounce takes a function and a wait time, and returns a new function. Two details are worth slowing down for:
timerlives outside the returned function, so it survives between calls. Each call can see, and cancel, the plan the previous call made. This is called a closure: the inner function keeps hold of variables from where it was created....argscollects whatever arguments the call received, andfn(...args)passes them on. The last call's arguments are the ones that win, so the search uses'Abu'.
clearTimeout(null) on the very first call does nothing, so you don't need a special case.
Step 4: connect it to the box
function debounce(fn, wait) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
const box = document.getElementById('box');
let keystrokes = 0;
const searches = [];
const search = debounce((value) => searches.push(value), 300);
box.addEventListener('input', (event) => {
keystrokes++;
search(event.target.value);
});
for (const partial of ['A', 'Ab', 'Abu', 'Abuj', 'Abuja']) {
box.value = partial;
box.dispatchEvent(new Event('input'));
}
setTimeout(() => console.log(keystrokes, searches), 400); // 5 ['Abuja']
Five keystrokes, one search, and it searched for the whole word. The cheap part (counting) runs on every keystroke. The expensive part (searching) waits.
Step 5: the wrong turn
A common slip is to create the debounced function inside the listener:
function debounce(fn, wait) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
const searches = [];
for (const partial of ['A', 'Ab', 'Abu']) {
debounce((value) => searches.push(value), 300)(partial);
}
setTimeout(() => console.log(searches), 400); // ['A', 'Ab', 'Abu']
Each call to debounce makes a brand-new timer, so no call can cancel another. Every keystroke still searches, just 300 milliseconds late. Call debounce once, outside the listener, and reuse the function it returns.
Step 6: testing without waiting
Real timers make tests slow, so the full solution lets you pass in the timer functions. It uses a pretend clock that the test moves forward by hand, so a 300 millisecond wait costs no real time.
function debounce(fn, wait, clock = {
setTimeout: (f, ms) => setTimeout(f, ms),
clearTimeout: (id) => clearTimeout(id),
}) {
let timer = null;
return (...args) => {
clock.clearTimeout(timer);
timer = clock.setTimeout(() => fn(...args), wait);
};
}
const d = debounce((v) => console.log('ran with', v), 50);
d(1);
d(2); // ran with 2
The default clock calls the real timers, so the page behaves normally. The full solution writes the default as { setTimeout, clearTimeout }, which works in Node, where its checks run. A browser expects its timer functions to be called on their own, not as a method of some other object, and can throw an "Illegal invocation" error. The small arrow functions above avoid that.
Debounce or throttle?
Debounce waits for quiet, then runs once. That suits a search box, where only the final value matters. Throttle is a different tool: it runs at most once every so often, however many events arrive. That suits scrolling or mouse movement, where you want steady updates while it's happening. A debounced scroll handler does nothing until scrolling stops, which feels broken.
The full solution
The panel types "Abuja" a letter at a time, 50 milliseconds apart, on a pretend clock. Its checks confirm five keystrokes give one search with the final value, a pause between words gives separate searches, only one timer is ever pending, the work waits for the full delay, arguments reach the function with the last call winning, and twenty rapid calls collapse into one. Press Run, then type quickly into the live demo and watch the two counts.
allow-scripts only, so it cannot reach this page.// ---- the stand-in ----------------------------------------------------------
// An injected clock, so a 300ms wait costs no real time.
function makeClock() {
let now = 0;
let jobs = [];
let nextId = 1;
return {
setTimeout(fn, ms) { const id = nextId++; jobs.push({ id, fn, at: now + ms }); return id; },
clearTimeout(id) { jobs = jobs.filter((j) => j.id !== id); },
pending: () => jobs.length,
advance(ms) {
now += ms;
const due = jobs.filter((j) => j.at <= now).sort((a, b) => a.at - b.at);
jobs = jobs.filter((j) => j.at > now);
for (const job of due) job.fn();
},
};
}
// ---- the answer ------------------------------------------------------------
function debounce(fn, wait, clock = { setTimeout, clearTimeout }) {
let timer = null;
return (...args) => {
clock.clearTimeout(timer); // cancel the previous plan
timer = clock.setTimeout(() => fn(...args), wait);
};
}
const clock = makeClock();
const box = el('input', { id: 'box' });
document.body.appendChild(box);
let keystrokes = 0;
const searches = [];
const search = debounce((value) => searches.push(value), 300, clock);
box.addEventListener('input', (event) => {
keystrokes++;
search(event.target.value);
});
const type = (text) => { box.value = text; fire(box, 'input'); };
// Typing "Abuja" one letter at a time, 50ms apart.
for (const partial of ['A', 'Ab', 'Abu', 'Abuj', 'Abuja']) {
type(partial);
clock.advance(50);
}
const keystrokesAfterWord = keystrokes; // snapshot: more typing happens below
console.log('mid-typing : keystrokes', keystrokes, '| searches', searches.length, '| pending', clock.pending());
clock.advance(300);
console.log('after quiet: keystrokes', keystrokes, '| searches', searches);
// A pause in the middle produces two searches.
type('L'); clock.advance(400);
type('La'); clock.advance(400);
console.log('with pauses:', searches);
Output
13 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 13 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('five keystrokes were seen while typing the word', keystrokesAfterWord, 5);
test('but they produced a single search', searches.filter((s) => s === 'Abuja').length, 1);
test('and it used the final value, not an early one', searches[0], 'Abuja');
test('no intermediate value was searched', searches.includes('Ab'), false);
test('a pause between words produces separate searches', searches, ['Abuja', 'L', 'La']);
test('nothing is left pending afterwards', clock.pending(), 0);
test('the timer is cleared on every call, so only one is ever pending', (() => { const c = makeClock(); const d = debounce(() => {}, 100, c); d(); d(); d(); return c.pending(); })(), 1);
test('the work does not run before the wait is up', (() => { const c = makeClock(); let ran = 0; const d = debounce(() => ran++, 100, c); d(); c.advance(99); return ran; })(), 0);
test('and does run once the wait passes', (() => { const c = makeClock(); let ran = 0; const d = debounce(() => ran++, 100, c); d(); c.advance(100); return ran; })(), 1);
test('arguments reach the debounced function', (() => { const c = makeClock(); let got = null; const d = debounce((a, b) => { got = [a, b]; }, 10, c); d(1, 2); c.advance(10); return got; })(), [1, 2]);
test('the LAST call\u2019s arguments win', (() => { const c = makeClock(); let got = null; const d = debounce((v) => { got = v; }, 10, c); d('first'); d('second'); c.advance(10); return got; })(), 'second');
test('twenty rapid calls collapse into one', (() => { const c = makeClock(); let ran = 0; const d = debounce(() => ran++, 50, c); for (let i = 0; i < 20; i++) { d(); c.advance(10); } c.advance(50); return ran; })(), 1);
test('no real time was spent waiting', true, true);
Adapted. The timer functions are a parameter defaulting to the real ones, so the page behaves normally and the test drives a fake clock. Twenty rapid calls collapsing into one is asserted in simulated time; the same test with real timers would take a second and be flaky.
clearTimeout before setTimeout on every call is the whole mechanism: each call cancels the previous plan, so only the last one survives. The assertion that only one timer is ever pending after three calls is the direct check of that.
Debounce and throttle are different tools and get confused constantly. Debounce waits for quiet — right for a search box, where only the final value matters. Throttle runs at a fixed maximum rate — right for scroll or mousemove, where you want steady updates rather than one at the end. Using debounce on a scroll handler produces an interface that does nothing until you stop, which feels broken.
Common mistakes
- Forgetting
clearTimeout. Every keystroke still runs the search, just late. - Creating the debounced function inside the listener. Each call gets its own timer, so nothing is ever cancelled. Create it once.
- Debouncing something that needs steady updates. For scroll or mouse movement, use throttling instead.
Try it yourself
- Show "searching..." while a search is waiting to run, and the result when it does.
- Skip the search entirely when the trimmed value is shorter than 2 characters.
- Write
throttle(fn, wait), which runsfnat most once everywaitmilliseconds, and compare it withdebounceon the same typing.