javascript 53 lines · 9 steps

Building a debounced autocomplete widget

A self-contained autocomplete that debounces typing and cancels stale requests as you search.

Explained by highlit
1function createAutocomplete(input, resultsList, { minChars = 2, delay = 300 } = {}) {
2 let timer = null;
3 let controller = null;
4 
5 async function fetchSuggestions(query) {
6 if (controller) controller.abort();
7 controller = new AbortController();
8 
9 try {
10 const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
11 signal: controller.signal,
12 headers: { Accept: 'application/json' },
13 });
14 if (!res.ok) throw new Error(`Search failed: ${res.status}`);
15 const suggestions = await res.json();
16 render(suggestions);
17 } catch (err) {
18 if (err.name !== 'AbortError') console.error(err);
19 }
20 }
21 
22 function render(suggestions) {
23 resultsList.replaceChildren();
24 for (const { id, label } of suggestions) {
25 const li = document.createElement('li');
26 li.textContent = label;
27 li.dataset.id = id;
28 li.setAttribute('role', 'option');
29 resultsList.appendChild(li);
30 }
31 resultsList.hidden = suggestions.length === 0;
32 }
33 
34 input.addEventListener('input', () => {
35 const query = input.value.trim();
36 clearTimeout(timer);
37 
38 if (query.length < minChars) {
39 resultsList.replaceChildren();
40 resultsList.hidden = true;
41 return;
42 }
43 
44 timer = setTimeout(() => fetchSuggestions(query), delay);
45 });
46 
47 resultsList.addEventListener('click', (e) => {
48 const li = e.target.closest('li[data-id]');
49 if (!li) return;
50 input.value = li.textContent;
51 resultsList.hidden = true;
52 });
53}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Debouncing with setTimeout avoids firing a request on every keystroke.
  2. 2AbortController cancels in-flight requests so slow responses can't overwrite fresh ones.
  3. 3Closures over timer and controller keep per-widget state private without a class.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a debounced autocomplete widget — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code