Katkat

Build an Autocomplete Search Bar With a Hand-Written Debounce

WaymoFrontend Engineer · Onsite

Last updated

Build an autocomplete search bar that fetches suggestions as the user types, with a hand-written debounce. Tests timer handling across renders, out-of-order responses and request cancellation, keyboard navigation, accessibility, cleanup and testing with fake timers.

Build an autocomplete search bar. As the user types, the component shows a list of suggestions for the current text, fetched from a suggestion service. Requests must be debounced, so the service is called only after the user pauses typing rather than on every keystroke. Write the debounce logic yourself instead of importing a utility library.

Assume the suggestion service is available as an asynchronous function (the name and signature are illustrative):

declare function fetchSuggestions(query: string, signal?: AbortSignal): Promise<string[]>;

Clarifying Questions

  • What debounce delay is expected, and should very short queries (for example one character) be sent at all?
  • What happens when a suggestion is chosen: fill the input, navigate somewhere, or trigger a search?
  • Is keyboard navigation of the list (arrow keys, Enter, Escape) required?
  • Should results be cached for queries the user has already typed?
  • Which framework, if any, should the component use?

Hints

Hint 1

Debounce is one timer: Work out what has to happen to the pending call each time a new keystroke arrives.

Hint 2

Responses arrive out of order: Suppose the request for "ca" returns after the request for "car". Decide what the user should see.

Follow-up questions

  • How is debounce different from throttle, and when would you choose throttle for this component?
  • The product wants the first keystroke to be answered immediately and only later ones debounced. What changes?
  • How would you highlight the part of each suggestion that matches the typed text safely?
  • How would you test the debounce and the out-of-order handling without waiting in real time?