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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Debouncing with setTimeout avoids firing a request on every keystroke.
- 2AbortController cancels in-flight requests so slow responses can't overwrite fresh ones.
- 3Closures over timer and controller keep per-widget state private without a class.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-debounced-autocomplete-widget-explained-javascript-de03/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.