Autocomplete Input with Debounce
An autocomplete box shows suggestions while someone types. The suggestions usually come from a server, so each lookup is asynchronous and returns a promise. Two problems follow from that:
- A lookup on every key press sends far more requests than needed, because most of them are out of date by the time they finish.
- Answers can arrive out of order, so a slow answer to an old query can replace the right suggestions with wrong ones.
Debouncing solves the first problem, and a request counter solves the second.
Debouncing a function
Section titled “Debouncing a function”A debounced function waits until calls have stopped for a set time, then runs once with the last arguments it was given. Each new call cancels the timer from the call before:
const debounce = (callback, ms) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => callback(...args), ms); };};
const search = debounce((text) => console.log(`Searching for "${text}"`), 200);
// Someone types "sage" with 50 ms between key presses, pauses, then types "mint".['s', 'sa', 'sag', 'sage'].forEach((text, i) => setTimeout(search, i * 50, text));['m', 'mi', 'min', 'mint'].forEach((text, i) => setTimeout(search, 600 + i * 50, text));This prints:
Searching for "sage"Searching for "mint"Eight calls lead to two searches, one for each pause in typing. The timer variable lives in a closure, so each debounced function keeps its own timer. A delay of 200 to 300 milliseconds is a common choice, because it is short enough to feel immediate and long enough to skip most key presses.
Ignoring answers that arrive late
Section titled “Ignoring answers that arrive late”Debouncing reduces the number of lookups but cannot stop them overlapping. Here the lookup for “c” takes longer than the later lookup for “ch”. Each call takes a number from a counter, and when its answer arrives, it is shown only if no newer call has started since:
const herbs = ['basil', 'chamomile', 'chervil', 'chives', 'coriander', 'dill'];
const findHerbs = (text, ms) => new Promise((resolve) => { setTimeout(() => resolve(herbs.filter((herb) => herb.startsWith(text))), ms); });
let latestRequest = 0;
const suggest = (text, ms) => { const request = ++latestRequest; findHerbs(text, ms).then((matches) => { if (request !== latestRequest) { console.log(`Ignoring old results for "${text}"`); return; } console.log(`Suggestions for "${text}":`, matches); });};
suggest('c', 300);suggest('ch', 100);This prints:
Suggestions for "ch": [ 'chamomile', 'chervil', 'chives' ]Ignoring old results for "c"Without the check, the answer for “c” would arrive last and replace the correct list. When the lookup uses fetch(), an AbortController can go further and cancel the older request, which saves the network traffic as well.
The whole box in a page
Section titled “The whole box in a page”This page puts the two ideas together. findHerbs() stands in for a server by answering after a random delay, which makes late answers likely:
<label for="herb-search">Search for a herb</label><input type="search" id="herb-search" autocomplete="off"><ul id="suggestions"></ul><script src="autocomplete.js"></script>const herbs = ['basil', 'bay', 'borage', 'chamomile', 'chervil', 'chives', 'coriander', 'dill', 'fennel', 'lovage', 'mint', 'oregano', 'parsley', 'rosemary', 'sage', 'sorrel', 'tarragon', 'thyme'];
// Stands in for a server, which answers after a random delay of up to 600 ms.const findHerbs = (text) => new Promise((resolve) => { const matches = herbs.filter((herb) => herb.startsWith(text.toLowerCase())); setTimeout(resolve, Math.random() * 600, matches); });
const debounce = (callback, ms) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => callback(...args), ms); };};
const input = document.querySelector('#herb-search');const list = document.querySelector('#suggestions');let latestRequest = 0;
const render = (items) => { list.replaceChildren( ...items.map((text) => { const item = document.createElement('li'); item.textContent = text; return item; }), );};
const showSuggestions = async (text) => { const request = ++latestRequest; const matches = text ? await findHerbs(text) : []; if (request !== latestRequest) { return; } render(text && matches.length === 0 ? ['No matches'] : matches);};
input.addEventListener('input', debounce(() => showSuggestions(input.value.trim()), 300));Typing “ch” into the box shows chamomile, chervil and chives about a third of a second after the last key press, plus the server’s delay. Typing a letter that matches nothing shows “No matches”, and clearing the box clears the list. The input event fires for every change, including pasting and deleting, which is why it is used rather than a keyboard event. Setting textContent rather than innerHTML keeps any text from the server from being read as HTML.
A production autocomplete also needs keyboard navigation and the ARIA combobox roles, so that it works with a keyboard and a screen reader.
Steve Griffith covers this topic in his video Build an Autocomplete Input with Debounce.