← Back to JavaScript, page 10

javascript-0184 · Hard senior

How would you design the client side of an autocomplete (typeahead) component so it is fast, correct, and accessible?

Debounce input, skip short queries, cancel the previous request with AbortController, ignore stale responses, cache results by normalized query, and keep a small state machine for idle, loading, ready, and error. Add keyboard navigation with the combobox ARIA pattern, handle IME composition, and track metrics. The key correctness issue is out-of-order responses, which cancellation and a request token solve.

Full answer

Clarify first: data size (local filter or server search), latency target, who is the user (keyboard, screen reader), and what a selection triggers.

Core design:

  1. Input handling: listen to input, normalize the query (trim, lowercase for the cache key), and wait for a minimum length (often 2 or 3 characters). Debounce by about 150 to 300 ms, shorter for local data. Do not search while an IME composition is in progress (compositionstart and compositionend).
  2. Request control: create an AbortController for each request and abort the previous one when a new request starts or the input is cleared. Also keep a request id (or compare the query) and ignore any response that is not for the latest query, because aborting is cooperative and a response may still arrive.
  3. State machine: idle, loading, ready, empty, error, with the items and an active index. Keep old results visible while loading the next ones to avoid flicker, and show a clear empty and error message.
  4. Cache: an LRU map keyed by normalized query, with a TTL. Prefix reuse is possible: results for "jav" can filter results for "java" locally when the server returns the complete set.
  5. Keyboard and accessibility: use the ARIA combobox pattern: role="combobox", aria-expanded, aria-controls the listbox, aria-activedescendant for the highlighted option, role="option" on items, arrow keys to move, Enter to select, Escape to close, and a live region that announces the number of results.
  6. Rendering: highlight the matched part with safe text nodes (never innerHTML with server text), limit the number of rows, and keep the list in a portal or positioned container so it is not clipped.
  7. Selection: close the list, put the label in the input, and do not start a new search for that programmatic change. Clear the selected value if the user edits the text afterwards.
  8. Resilience: timeouts, retry on network errors only, and a fallback to recent searches when offline.
  9. Server cooperation: ranking, typo tolerance, and rate limits belong to the server. The client should send a client request id and the query only, and handle HTTP 429.
  10. Measure: time to first suggestion, cancel rate, cache hit rate, and selection position.

Trade-offs: a lower debounce feels faster but sends more requests, aggressive caching shows stale suggestions, and prefetching popular queries costs bandwidth.

javascript
function createAutocomplete({ search, debounceMs = 40, minChars = 2, cacheSize = 10, log }) {
  const cache = new Map();
  let timer = null;
  let controller = null;
  let latest = 0;
  const state = { query: '', status: 'idle', items: [], active: -1 };
  const emit = () => log(`${state.status.padEnd(7)} query="${state.query}" items=${JSON.stringify(state.items)}`);

  function remember(key, items) {
    cache.delete(key);
    cache.set(key, items);
    if (cache.size > cacheSize) cache.delete(cache.keys().next().value);
  }

  async function run(key) {
    if (cache.has(key)) {
      const items = cache.get(key);
      remember(key, items);
      Object.assign(state, { status: 'ready', items, active: -1 });
      return emit();
    }
    controller?.abort();
    controller = new AbortController();
    const mine = ++latest;
    state.status = 'loading';
    emit();
    try {
      const items = await search(key, { signal: controller.signal });
      if (mine !== latest) return;
      remember(key, items);
      Object.assign(state, { status: items.length ? 'ready' : 'empty', items, active: -1 });
    } catch (error) {
      if (error.name === 'AbortError' || mine !== latest) return;
      Object.assign(state, { status: 'error', items: [] });
    }
    emit();
  }

  return {
    state,
    setQuery(raw) {
      state.query = raw;
      clearTimeout(timer);
      const key = raw.trim().toLowerCase();
      if (key.length < minChars) {
        controller?.abort();
        latest++;
        Object.assign(state, { status: 'idle', items: [], active: -1 });
        return;
      }
      timer = setTimeout(() => run(key), debounceMs);
    },
    move(delta) {
      const n = state.items.length;
      if (!n) return -1;
      state.active = (state.active + delta + n + (state.active === -1 && delta < 0 ? 1 : 0)) % n;
      return state.active;
    },
    select() {
      return state.items[state.active];
    },
  };
}

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const latency = { jav: 200, java: 20, jav2: 20 };
const data = { jav: ['java', 'javascript'], java: ['java', 'java lang', 'javascript'] };
let calls = 0;
const search = (query, { signal }) =>
  new Promise((resolve, reject) => {
    calls++;
    const timer = setTimeout(() => resolve(data[query] ?? []), latency[query] ?? 10);
    signal?.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
    });
  });

(async () => {
  console.log('--- naive: no abort, no latest check ---');
  let naive = [];
  const naiveSearch = (q) => search(q, {}).then((items) => (naive = items));
  naiveSearch('jav');
  await wait(20);
  naiveSearch('java');
  await wait(300);
  console.log('naive final list for "java":', JSON.stringify(naive));

  console.log('--- with cancellation and a latest check ---');
  calls = 0;
  const box = createAutocomplete({ search, log: (line) => console.log(line) });
  box.setQuery('j');
  box.setQuery('jav');
  await wait(70);
  box.setQuery('java');
  await wait(250);
  console.log('requests sent:', calls, '| final:', JSON.stringify(box.state.items));

  box.setQuery('java ');
  await wait(100);
  console.log('cache hit, requests sent:', calls);
  console.log('keyboard:', box.move(1), box.move(1), box.move(-1), box.move(-1), box.move(-1), '| select:', box.select());
  box.setQuery('');
  console.log('cleared:', box.state.status);
})();

Run with Node.js v24.22.1 as js-184.js; two runs gave identical output. Output: --- naive: no abort, no latest check --- naive final list for "java": ["java","javascript"] --- with cancellation and a latest check --- loading query="jav" items=[] loading query="java" items=[] ready query="java" items=["java","java lang","javascript"] requests sent: 2 | final: ["java","java lang","javascript"] ready query="java " items=["java","java lang","javascript"] cache hit, requests sent: 2 keyboard: 0 1 0 2 1 | select: java lang cleared: idle

Key points

  • Debounce, minimum length, and IME handling reduce useless requests.
  • AbortController plus a latest-request check prevents out-of-order results.
  • A small state machine with kept previous results avoids flicker.
  • LRU cache with TTL, keyed by normalized query.
  • Use the ARIA combobox pattern, keyboard support, safe rendering, and metrics.

Common mistakes

  • Sending a request on every keystroke with no debounce or minimum length.
  • Letting an older, slower response overwrite newer results.
  • Building the list with innerHTML from server text.
  • Ignoring keyboard users and screen readers.

Follow-ups

  • How would you reuse the results of a shorter prefix?
  • What changes if the data set is small enough to filter locally?
  • How do you test race conditions in this component?

Tips

  • Name out-of-order responses as the main bug and show two defenses.
  • Cover accessibility: it separates strong answers.
  • Mention metrics and server cooperation.