Debounced Combobox Autocomplete with Async Cancellation

Medium · Software Engineering Fundamentals · Frontend Engineer · Onsite

Problem Statement

Implement a deterministic, clock-driven state machine for an accessible combobox autocomplete widget that coordinates input debouncing, in-flight request cancellation, out-of-order network responses, keyboard navigation, and WAI-ARIA screen-reader attributes.

Provide AbortSignal, AbortController, and Autocomplete matching these contracts:

  1. AbortSignal & AbortController
    • AbortSignal() initializes self.aborted = False.
    • AbortController() creates self.signal = AbortSignal(), and abort() -> None flips self.signal.aborted = True.
  2. Autocomplete(fetch_suggestions, delay_ms=300, list_id="ac-listbox")
    • on_input(value: str, now_ms: int) -> None: Record raw value, clear any keyboard highlight, cancel any pending debounce timer, and examine query = value.strip().
      • If query == "" (empty or whitespace-only), immediately abort any active network call, clear cached suggestions, collapse the listbox, and set status = "idle".
      • Otherwise schedule query to be fetched once the clock reaches now_ms + delay_ms.
    • advance_to(now_ms: int) -> None: Advance logical time (milliseconds). Whenever a debounce timer is pending and now_ms >= timer_due, clear the timer, abort any still-active earlier request, create a fresh AbortController, set status = "loading", and invoke fetch_suggestions(query, controller.signal).
    • on_response(signal: AbortSignal, items: List[str]) -> bool: Process items only if signal belongs to the single currently active request; return False without changing UI state if stale or cancelled. When current, clear the active controller, store items linked to that request's trimmed query, clear keyboard highlight, set status = "ready" and expand the popup when items is non-empty (or set status = "empty" and collapse the popup when items is empty), and return True.
    • on_error(signal: AbortSignal, message: str) -> bool: Process the failure only if signal belongs to the currently active request (silently returning False for aborted or superseded requests). When current, clear the active controller, clear options, collapse the popup, clear highlight, set status = "error", and return True.
    • on_keydown(key: str) -> Optional[str]:
      • "ArrowDown" / "ArrowUp": If no options are stored, return None. When collapsed, reopen (0 for "ArrowDown", len(options) - 1 for "ArrowUp") only if the stored options match value.strip(); otherwise stay collapsed and return None. When already expanded, cycle the highlight with wrap-around (if expanded with no option highlighted yet, "ArrowDown" highlights 0 and "ArrowUp" highlights len(options) - 1). Return None.
      • "Enter": If expanded with an active highlight, select that option and return its text; otherwise return None.
      • "Escape": Call close() and return None.
    • select(index: int) -> str: Set value = options[index], call close() without scheduling a new search, and return the chosen string.
    • on_blur() -> None: Call close().
    • close() -> None: Cancel any pending timer, abort any active request, collapse the popup, clear highlight, and set status = "idle".
    • render() -> Dict[str, Any]: Return the WAI-ARIA view dictionary:
      • "value": current input string,
      • "role": "combobox",
      • "aria-autocomplete": "list",
      • "aria-controls": list_id,
      • "aria-expanded": "true" when expanded else "false",
      • "aria-activedescendant": f"{list_id}-option-{active}" when expanded with an active highlight, else "",
      • "options": [{"id": f"{list_id}-option-{i}", "text": text, "aria-selected": "true" or "false"}, ...] while expanded, or [] while collapsed,
      • "status": "idle", "loading", "ready", "empty", or "error",
      • "message": "1 suggestion available", f"{N} suggestions available", "No suggestions" ("empty"), "Suggestions could not be loaded" ("error"), or "" ("idle" / "loading").

Examples

Example 1

Input:

ac = Autocomplete(fetch_suggestions, delay_ms=250, list_id="city-list")
ac.on_input("s", 0)
ac.on_input("se", 120)
ac.advance_to(300)   # not due yet (120 + 250 = 370)
ac.advance_to(370)   # triggers fetch_suggestions("se", s1)
ac.on_response(s1, ["seattle", "seoul"])
ac.on_keydown("ArrowDown")
ac.on_keydown("ArrowDown")
chosen = ac.on_keydown("Enter")

Output:

chosen == "seoul"
ac.render()["value"] == "seoul"
ac.render()["aria-expanded"] == "false"

Explanation: Typing "se" at 120 ms resets the 250 ms quiet window to 370 ms, so "s" never fires a network call. Once ["seattle", "seoul"] arrives, two "ArrowDown" presses highlight index 1 ("city-list-option-1"), and "Enter" commits "seoul" and closes the popup without starting another fetch.

Example 2

Input:

ac = Autocomplete(fetch_suggestions, delay_ms=300)
ac.on_input("py", 0)
ac.advance_to(300)    # starts request 1 ("py", s1)
ac.on_input("pyt", 400)
ac.advance_to(700)    # aborts s1, starts request 2 ("pyt", s2)
applied_new = ac.on_response(s2, ["python", "pytest"])
applied_old = ac.on_response(s1, ["pypy", "pyramid", "pydantic"])

Output:

s1.aborted is True
(applied_new, applied_old) == (True, False)
[opt["text"] for opt in ac.render()["options"]] == ["python", "pytest"]

Explanation: Launching "pyt" at 700 ms cancels s1 (s1.aborted = True). Even when the stale "py" callback resolves after "pyt" has rendered, on_response rejects s1 by signal identity so ["python", "pytest"] stays visible.

Constraints

  • delay_ms >= 0
  • Timestamps passed to on_input and advance_to are non-decreasing integer milliseconds.
  • Leading and trailing whitespace in value is stripped before deciding whether a query is blank or passing it to fetch_suggestions, while render()["value"] preserves the exact value string typed or selected.
  • fetch_suggestions may invoke on_response or on_error in any order, or ignore signal.aborted.

Step-by-step walkthrough

  1. Model the combobox as an explicit clock-and-signal state machine

    An autocomplete widget looks straightforward until four independent event streams interleave in arbitrary order:

    1. Text edits (on_input),
    2. Timer ticks (advance_to),
    3. Out-of-order network callbacks or errors (on_response, on_error),
    4. Keyboard, click, and focus events (on_keydown, select, on_blur, close).

    Every subtle UI bug — firing an API call per keystroke, letting a slow "py" response overwrite fresher "pyt" options, showing an error banner when an obsolete fetch is cancelled, or popping open suggestions after Escape — happens when an older async event overwrites newer state.

    Separating pure state transitions from browser globals (setTimeout, fetch, DOM elements) makes every race deterministic and unit-testable:

    User / Clock / Network Events                 Autocomplete State
    -----------------------------                 ------------------
    on_input(value, now_ms)    ---\               value, options, options_query
    advance_to(now_ms)         ----+--> updates   expanded, active, status
    on_response / on_error     ---/               timer_due, pending_query
    on_keydown / select / blur --/                request_query, controller
                                                         |
                                                         v
                                            render() -> ARIA + UI view dict
    
    class AbortSignal:
        """Lightweight stand-in for the browser's AbortSignal; aborted flips to True on cancel."""
    
        def __init__(self):
            self.aborted = False
    
    
    class AbortController:
        """Same idea as the browser's AbortController: abort() flips the shared signal."""
    
        def __init__(self):
            self.signal = AbortSignal()
    
        def abort(self) -> None:
            self.signal.aborted = True
    

    Inside Autocomplete.__init__, we track three separate query strings (pending_query, request_query, options_query) so we always know which trimmed string is waiting on the timer, which string is mid-flight over the network, and which string produced the items currently stored in self.options:

    class Autocomplete:
        def __init__(self, fetch_suggestions: Callable[[str, AbortSignal], Any],
                     delay_ms: int = 300, list_id: str = "ac-listbox"):
            self.fetch_suggestions = fetch_suggestions
            self.delay_ms = delay_ms
            self.list_id = list_id
    
            # UI state: raw input text, current suggestion strings, and which trimmed query they belong to
            self.value = ""
            self.options: List[str] = []      # e.g. ["python", "pytest"]
            self.options_query = ""           # trimmed query that produced self.options, e.g. "pyt"
            self.expanded = False             # True only when the suggestion popup is visible
            self.active = -1                  # index in self.options of highlighted item, or -1 for none
            self.status = "idle"              # one of: "idle" | "loading" | "ready" | "empty" | "error"
    
            # Async coordination state: at most one pending debounce timer and at most one current request
            self.timer_due: Optional[int] = None      # timestamp (ms) when debounce fires, or None
            self.pending_query = ""                   # trimmed query waiting on the debounce timer
            self.request_query = ""                   # trimmed query of the currently active network call
            self.controller: Optional[AbortController] = None
    
  2. Coalesce rapid typing with debouncing and handle blank input

    Debouncing delays firing a request until delay_ms of quiet time have elapsed since the latest edit. Whenever another keystroke arrives before timer_due, we replace the deadline with now_ms + delay_ms:

    Example 1 (delay_ms = 250 ms):
    t =   0 ms: user types "s"   -> timer_due = 250
    t = 120 ms: user types "se"  -> cancel 250, new timer_due = 370
    t = 300 ms: clock reaches 300 -> nothing fires (300 < 370)
    t = 370 ms: clock reaches 370 -> timer fires ONCE: fetch_suggestions("se", s1)
    

    Two details in on_input prevent subtle bugs:

    • Reset self.active = -1 on every edit: if the user highlighted row 1 from an earlier list and typed another character, pressing Enter must not select the old row.
    • Blank or whitespace-only input: if value.strip() == "", cancel the timer and abort any active request immediately so a slow network reply cannot pop open suggestions underneath an empty input field.
        def on_input(self, value: str, now_ms: int) -> None:
            self.value = value
            # Reset keyboard highlight whenever text changes so Enter cannot pick an old row by mistake.
            self.active = -1
            self._clear_timer()
    
            query = value.strip()
            if query == "":
                # Rapid deletion / whitespace-only input: cancel in-flight work immediately so a late
                # network response cannot pop open suggestions underneath an empty input box.
                self._abort_request()
                self.options = []
                self.options_query = ""
                self.expanded = False
                self.status = "idle"
                return
    
            # Restart the debounce window from this keystroke's timestamp.
            self.pending_query = query
            self.timer_due = now_ms + self.delay_ms
    
        def advance_to(self, now_ms: int) -> None:
            # Use '>=' so the request fires right on the exact millisecond timer_due is reached.
            if self.timer_due is not None and now_ms >= self.timer_due:
                self.timer_due = None
                self._start_request(self.pending_query)
    
  3. Eliminate network races with cancellation plus signal identity

    When "py" launches at 300 ms and "pyt" launches at 700 ms, the slower "py" response can arrive after "pyt" has already rendered. We guard against stale updates at two levels:

    1. Active cancellation (abort()): _start_request aborts the previous AbortController before creating a new one, flipping old_signal.aborted = True so HTTP clients can drop the obsolete socket.
    2. Signal identity check (_is_current): even if a caller ignores signal.aborted, self.controller is not None and self.controller.signal is signal guarantees that only the single active request can mutate options or status.

    The same _is_current(signal) guard inside on_error silently drops AbortError rejections from cancelled requests while surfacing genuine failures on the active request:

        def _start_request(self, query: str) -> None:
            # Cancel any still-running older request before creating the new AbortController.
            self._abort_request()
            controller = AbortController()
            self.controller = controller
            self.request_query = query
            self.status = "loading"
            self.fetch_suggestions(query, controller.signal)
    
        def _is_current(self, signal: AbortSignal) -> bool:
            # Identity check ('is') guarantees stale callbacks are ignored even if fetch_suggestions
            # forgot to honor signal.aborted.
            return self.controller is not None and self.controller.signal is signal
    
        def on_response(self, signal: AbortSignal, items: List[str]) -> bool:
            """Apply the answer only if `signal` belongs to the latest active request."""
            if not self._is_current(signal):
                return False
    
            self.controller = None
            self.options = list(items)
            self.options_query = self.request_query
            self.active = -1
            if len(self.options) > 0:
                self.status = "ready"
                self.expanded = True
            else:
                self.status = "empty"
                self.expanded = False
            return True
    
        def on_error(self, signal: AbortSignal, message: str) -> bool:
            """Show an error only for the active request; ignore stale/aborted request rejections."""
            if not self._is_current(signal):
                return False
    
            self.controller = None
            self.options = []
            self.options_query = ""
            self.expanded = False
            self.active = -1
            self.status = "error"
            return True
    
  4. Close cleanly on Escape, blur, and selection

    Pressing Escape, blurring the input (on_blur), and selecting an item (select) all share close(), which clears timer_due and aborts controller so no late response can reopen a dismissed popup. select(index) copies self.options[index] into self.value and calls close() without scheduling a new debounce timer:

        def select(self, index: int) -> str:
            """Click or Enter on an option: fill the input and close without starting a new search."""
            selected_text = self.options[index]
            self.value = selected_text
            self.close()
            return selected_text
    
        def on_blur(self) -> None:
            self.close()
    
        def close(self) -> None:
            """Hide the list and cancel both timer and in-flight fetch so late answers stay ignored."""
            self._clear_timer()
            self._abort_request()
            self.expanded = False
            self.active = -1
            self.status = "idle"
    
  5. Navigate with arrow keys and render WAI-ARIA combobox attributes

    In a WAI-ARIA combobox, DOM focus remains inside the text input while aria-activedescendant points to the id of the highlighted option (aria-selected="true"). Two keyboard subtleties matter in on_keydown:

    1. Reopening a dismissed popup: pressing ArrowDown or ArrowUp while collapsed reopens cached self.options only if self.options_query == self.value.strip() (blocking stale "py" items if the user typed "pyt" and pressed Escape).
    2. Initial ArrowUp when self.active == -1: right after options arrive, active is -1. Checking elif self.active <= 0: self.active = n - 1 cleanly sends both active == -1 (freshly opened list) and active == 0 (wrap-around from the top) to n - 1 (whereas (-1 - 1) % n would mistakenly jump to n - 2!):
    3 options (n = 3), starting at active = -1 (expanded = True):
    key         ArrowDown -> ArrowDown -> ArrowDown -> ArrowDown -> ArrowUp -> ArrowUp
    active idx      0     ->     1     ->     2     ->     0     ->    2    ->    1
    
        def on_keydown(self, key: str) -> Optional[str]:
            """Handle ArrowDown, ArrowUp, Enter, and Escape. Returns the selected text on Enter."""
            n = len(self.options)
            if key == "ArrowDown" or key == "ArrowUp":
                if n == 0:
                    return None
    
                if not self.expanded:
                    # Only reopen cached options if they still match the input's current trimmed text
                    # (prevents showing old "py" options after the user typed "pyt" and pressed Escape).
                    if self.options_query != self.value.strip():
                        return None
                    self.expanded = True
                    self.active = 0 if key == "ArrowDown" else n - 1
                elif key == "ArrowDown":
                    # When active == -1 (list just opened), (-1 + 1) % n == 0 selects the first option.
                    self.active = (self.active + 1) % n
                elif self.active <= 0:
                    # Covers BOTH active == -1 (no row highlighted yet -> start at bottom n - 1)
                    # and active == 0 (wrap from top row around to bottom row n - 1).
                    # Note: (self.active - 1) % n would fail for active == -1, giving n - 2!
                    self.active = n - 1
                else:
                    self.active -= 1
            elif key == "Enter":
                if self.expanded and self.active >= 0:
                    return self.select(self.active)
            elif key == "Escape":
                self.close()
            return None
    
  6. Trace Example 2's out-of-order race step by step

    time (ms)  event                                      timer_due  controller  UI state
    ---------  -----------------------------------------  ---------  ----------  --------------------------
       0       on_input("py", 0)                             300     None        idle, expanded=False
     300       advance_to(300) -> fetch("py", s1)            None    c1 (s1)     loading
     400       on_input("pyt", 400)                          700     c1 (s1)     loading (timer restarted)
     700       advance_to(700) -> abort c1,
               fetch("pyt", s2)                              None    c2 (s2)     loading (s1.aborted=True)
     740       on_response(s2, ["python", "pytest"])         None    None        ready, ["python", "pytest"]
     780       on_response(s1, ["pypy", "pyramid", ...])     None    None        IGNORED (s1 is not current)
    

    At 780 ms, _is_current(s1) returns False, keeping ["python", "pytest"] intact.

  7. Equivalent browser JavaScript wiring

    Every field of the Python state machine maps directly onto browser DOM APIs:

    • timer_due maps to clearTimeout(timerId) + setTimeout(..., delayMs);
    • _is_current(signal) maps to controller === currentController inside .then() and .catch();
    • Calling event.preventDefault() on the listbox's mousedown event keeps focus inside the <input> so clicking an option is not swallowed by blur;
    • Writing item.textContent = options[i] (never innerHTML) prevents cross-site scripting (XSS).
  8. Complete solution

    from typing import Any, Callable, Dict, List, Optional
    
    
    class AbortSignal:
        """Lightweight stand-in for the browser's AbortSignal; aborted flips to True on cancel."""
    
        def __init__(self):
            self.aborted = False
    
    
    class AbortController:
        """Same idea as the browser's AbortController: abort() flips the shared signal."""
    
        def __init__(self):
            self.signal = AbortSignal()
    
        def abort(self) -> None:
            self.signal.aborted = True
    
    
    class Autocomplete:
        """The logic of a debounced WAI-ARIA combobox, with time and the network made explicit.
    
        - on_input(value, now_ms) is the input event at time now_ms (milliseconds).
        - advance_to(now_ms) moves the clock; the debounce timer fires if it is due.
        - When a request starts, fetch_suggestions(query, signal) is called. The network answers
          later, in any order, through on_response(signal, items) or on_error(signal, message).
        """
    
        def __init__(self, fetch_suggestions: Callable[[str, AbortSignal], Any],
                     delay_ms: int = 300, list_id: str = "ac-listbox"):
            self.fetch_suggestions = fetch_suggestions
            self.delay_ms = delay_ms
            self.list_id = list_id
    
            # UI state: raw input text, current suggestion strings, and which trimmed query they belong to
            self.value = ""
            self.options: List[str] = []      # e.g. ["python", "pytest"]
            self.options_query = ""           # trimmed query that produced self.options, e.g. "pyt"
            self.expanded = False             # True only when the suggestion popup is visible
            self.active = -1                  # index in self.options of highlighted item, or -1 for none
            self.status = "idle"              # one of: "idle" | "loading" | "ready" | "empty" | "error"
    
            # Async coordination state: at most one pending debounce timer and at most one current request
            self.timer_due: Optional[int] = None      # timestamp (ms) when debounce fires, or None
            self.pending_query = ""                   # trimmed query waiting on the debounce timer
            self.request_query = ""                   # trimmed query of the currently active network call
            self.controller: Optional[AbortController] = None
    
        # ----- Phase 1: User typing and debounce clock ---------------------------
        def on_input(self, value: str, now_ms: int) -> None:
            self.value = value
            # Reset keyboard highlight whenever text changes so Enter cannot pick an old row by mistake.
            self.active = -1
            self._clear_timer()
    
            query = value.strip()
            if query == "":
                # Rapid deletion / whitespace-only input: cancel in-flight work immediately so a late
                # network response cannot pop open suggestions underneath an empty input box.
                self._abort_request()
                self.options = []
                self.options_query = ""
                self.expanded = False
                self.status = "idle"
                return
    
            # Restart the debounce window from this keystroke's timestamp.
            self.pending_query = query
            self.timer_due = now_ms + self.delay_ms
    
        def advance_to(self, now_ms: int) -> None:
            # Use '>=' so the request fires right on the exact millisecond timer_due is reached.
            if self.timer_due is not None and now_ms >= self.timer_due:
                self.timer_due = None
                self._start_request(self.pending_query)
    
        # ----- Phase 2: Keyboard, click, blur, and Escape ------------------------
        def on_keydown(self, key: str) -> Optional[str]:
            """Handle ArrowDown, ArrowUp, Enter, and Escape. Returns the selected text on Enter."""
            n = len(self.options)
            if key == "ArrowDown" or key == "ArrowUp":
                if n == 0:
                    return None
    
                if not self.expanded:
                    # Only reopen cached options if they still match the input's current trimmed text
                    # (prevents showing old "py" options after the user typed "pyt" and pressed Escape).
                    if self.options_query != self.value.strip():
                        return None
                    self.expanded = True
                    self.active = 0 if key == "ArrowDown" else n - 1
                elif key == "ArrowDown":
                    # When active == -1 (list just opened), (-1 + 1) % n == 0 selects the first option.
                    self.active = (self.active + 1) % n
                elif self.active <= 0:
                    # Covers BOTH active == -1 (no row highlighted yet -> start at bottom n - 1)
                    # and active == 0 (wrap from top row around to bottom row n - 1).
                    # Note: (self.active - 1) % n would fail for active == -1, giving n - 2!
                    self.active = n - 1
                else:
                    self.active -= 1
            elif key == "Enter":
                if self.expanded and self.active >= 0:
                    return self.select(self.active)
            elif key == "Escape":
                self.close()
            return None
    
        def select(self, index: int) -> str:
            """Click or Enter on an option: fill the input and close without starting a new search."""
            selected_text = self.options[index]
            self.value = selected_text
            self.close()
            return selected_text
    
        def on_blur(self) -> None:
            self.close()
    
        def close(self) -> None:
            """Hide the list and cancel both timer and in-flight fetch so late answers stay ignored."""
            self._clear_timer()
            self._abort_request()
            self.expanded = False
            self.active = -1
            self.status = "idle"
    
        # ----- Phase 3: Out-of-order network responses and errors ----------------
        def on_response(self, signal: AbortSignal, items: List[str]) -> bool:
            """Apply the answer only if `signal` belongs to the latest active request."""
            if not self._is_current(signal):
                return False
    
            self.controller = None
            self.options = list(items)
            self.options_query = self.request_query
            self.active = -1
            if len(self.options) > 0:
                self.status = "ready"
                self.expanded = True
            else:
                self.status = "empty"
                self.expanded = False
            return True
    
        def on_error(self, signal: AbortSignal, message: str) -> bool:
            """Show an error only for the active request; ignore stale/aborted request rejections."""
            if not self._is_current(signal):
                return False
    
            self.controller = None
            self.options = []
            self.options_query = ""
            self.expanded = False
            self.active = -1
            self.status = "error"
            return True
    
        # ----- Phase 4: WAI-ARIA combobox view projection ------------------------
        def render(self) -> Dict[str, Any]:
            rendered_options = []
            if self.expanded:
                for i, text in enumerate(self.options):
                    is_selected = "true" if i == self.active else "false"
                    rendered_options.append({
                        "id": self._option_id(i),
                        "text": text,
                        "aria-selected": is_selected,
                    })
    
            active_id = ""
            if self.expanded and self.active >= 0:
                active_id = self._option_id(self.active)
    
            return {
                "value": self.value,
                "role": "combobox",
                "aria-autocomplete": "list",
                "aria-controls": self.list_id,
                "aria-expanded": "true" if self.expanded else "false",
                "aria-activedescendant": active_id,
                "options": rendered_options,
                "status": self.status,
                "message": self._message(),
            }
    
        # ----- Internal helpers --------------------------------------------------
        def _start_request(self, query: str) -> None:
            # Cancel any still-running older request before creating the new AbortController.
            self._abort_request()
            controller = AbortController()
            self.controller = controller
            self.request_query = query
            self.status = "loading"
            self.fetch_suggestions(query, controller.signal)
    
        def _is_current(self, signal: AbortSignal) -> bool:
            # Identity check ('is') guarantees stale callbacks are ignored even if fetch_suggestions
            # forgot to honor signal.aborted.
            return self.controller is not None and self.controller.signal is signal
    
        def _abort_request(self) -> None:
            if self.controller is not None:
                self.controller.abort()
                self.controller = None
    
        def _clear_timer(self) -> None:
            self.timer_due = None
    
        def _option_id(self, index: int) -> str:
            return f"{self.list_id}-option-{index}"
    
        def _message(self) -> str:
            """Polite live-region announcement text for screen readers."""
            if self.status == "ready":
                count = len(self.options)
                if count == 1:
                    return "1 suggestion available"
                return f"{count} suggestions available"
            if self.status == "empty":
                return "No suggestions"
            if self.status == "error":
                return "Suggestions could not be loaded"
            return ""
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of an autocomplete box like taking food orders at a counter when a customer keeps revising what they want mid-sentence ("ramen... actually, spicy miso ramen"). A disciplined cashier does three things: waits a short beat to confirm the customer paused (debouncing, delaying an action until delay_ms of quiet time have elapsed since the latest event), tears up the old ticket whenever a newer ticket starts (cancellation via AbortController, whose .abort() method signals an in-flight network request to stop), and checks the ticket number before serving so a slower old order never replaces a newer one (preventing a race condition, where overlapping async tasks finish out of order and corrupt UI state).

Firing a network call on every keystroke and unconditionally rendering inside .then(render) breaks in three ways. First, a quick 8-letter word triggers 8 server calls instead of 1. Second, if "py" hits a slow backend shard and resolves after "pyt" has rendered, "last response wins" overwrites "pyt"'s suggestions with stale "py" items. Third, deleting the text or pressing Escape while a fetch is still running lets the late response pop the dropdown back open under an empty or dismissed box.

Our state machine maintains at most one pending timer (timer_due) and at most one active AbortController (controller), and projects a WAI-ARIA combobox view (the screen-reader pattern where real focus stays inside the input while aria-activedescendant points to the highlighted option's id and a polite ARIA live region announces result counts). Trace Example 2 (delay_ms = 300):

  1. t = 0 ms, user types "py": timer_due becomes 300; no network call yet.
  2. t = 300 ms, timer fires: c1 = AbortController() becomes self.controller, starting fetch_suggestions("py", c1.signal).
  3. t = 400 ms, user types "pyt": timer_due advances to 700 and active resets to -1.
  4. t = 700 ms, timer fires: c1.abort() cancels "py", c2 = AbortController() replaces self.controller, and fetch_suggestions("pyt", c2.signal) starts.
  5. t = 740 ms (c2 resolves) then t = 780 ms (c1 resolves late): c2.signal matches self.controller.signal, rendering ["python", "pytest"] and clearing self.controller = None; 40 ms later c1.signal fails _is_current and is ignored.

Complexity

  • Time: O(1) per input edit, clock advance, or key press, and O(n) per network response or render(), where n is the number of returned suggestions. Updating timer_due, aborting controller, and cycling self.active touch a constant number of scalar fields, while on_response and render loop once across the n visible options. Across a burst of k keystrokes spaced closer than delay_ms, debouncing collapses k edits into 1 network call.
  • Space: O(n). State holds only the current list of n suggestion strings, scalar status fields, one timer deadline, and at most one active AbortController.

Edge cases

  • Out-of-order stale response ("py" arriving after "pyt"): blocked by _is_current(signal) via object identity (is), even if fetch_suggestions ignores signal.aborted.
  • AbortError rejection on cancelled requests: when _abort_request() aborts an older AbortController, _is_current(old_signal) is False, keeping normal cancellations silent instead of flashing "Suggestions could not be loaded".
  • Cleared or whitespace-only input ("" or " "): on_input strips whitespace, cancels the timer, aborts any active request, empties options, and resets status = "idle".
  • Empty suggestion list ([]): expanded becomes False and status becomes "empty" with live-region message "No suggestions".
  • ArrowUp on a freshly opened list (active == -1): self.active <= 0 -> n - 1 highlights the bottom option n - 1 rather than miscomputing (-1 - 1) % n = n - 2.
  • Escape or blur mid-fetch followed by ArrowDown: close() aborts the request, and on_keydown verifies self.options_query == self.value.strip() before reopening so old "py" items cannot reopen under "pyt".
  • Enter with no highlighted row (active == -1): returns None so standard form submission still works when submitting typed text directly.

Common mistakes

  • "Last response wins" instead of "latest request wins": mutating options unconditionally inside .then() lets slow earlier prefixes overwrite fast newer prefixes.
  • Skipping the signal identity check after abort(): mocks or custom wrappers that resolve despite signal.aborted will still overwrite state unless you verify self.controller.signal is signal.
  • Surfacing AbortError as a network failure: user-driven cancellation during typing is normal operation and must stay silent.
  • Confusing throttling with debouncing: throttling fires every delay_ms during continuous typing, whereas debouncing waits until typing pauses for delay_ms.
  • Losing mouse clicks on options to blur: in browsers, mousedown -> input.blur -> mouseup -> click; without event.preventDefault() on listbox mousedown, blur hides the list before click fires.
  • Rendering suggestions via innerHTML: untrusted completion strings trigger cross-site scripting (XSS); always assign textContent.

Follow-up questions

  • How can you add a client-side response cache so repeated prefixes do not trigger duplicate API calls? Key a bounded LRU (least-recently-used) cache Map by normalized query (query.trim().toLowerCase()) storing { items, expiresAt } with a short TTL (time-to-live) such as 60 s. Check the cache when the debounce timer fires: on a fresh hit, abort any active network call and apply the cached items immediately with zero network traffic; when a network call succeeds, store items (never errors) in the cache before the staleness check so even a superseded response warms the cache if the user backspaces to that prefix.

```javascript const cache = new Map(); // normalizedQuery -> { items, expiresAt }

function getCached(query) { const entry = cache.get(query); if (!entry) return null; if (Date.now() > entry.expiresAt) { cache.delete(query); return null; } cache.delete(query); // move hit to most-recently-used end cache.set(query, entry); return entry.items; } ```

  • What adjustments are needed for CJK Input Method Editors (IME) so phonetic composition keystrokes do not fire premature searches or steal Enter/Arrow keys? During IME composition (where multiple phonetic keystrokes assemble Japanese, Chinese, or Korean characters in an OS candidate window), browsers set event.isComposing === true on 'input' and 'keydown' events until 'compositionend' fires. Ignore 'input' events while event.isComposing is true, invoke onInput() once inside 'compositionend' with the committed characters, and skip combobox keydown handling whenever event.isComposing || event.keyCode === 229 so Enter and arrow keys control the OS IME popup rather than the autocomplete list.

  • How do you prevent race bugs and dropped option clicks when focus rapidly enters and leaves the input box? Focusing the input alone should never start a network call or reopen stale items, while blur synchronously calls close(), clearing timer_due and aborting controller so tabbing past the field never leaks timers or pops suggestions over neighboring inputs. Avoid setTimeout(close, 200) workarounds on blur—a delayed blur timer races with rapid re-focusing and wipes out freshly typed queries; instead keep blur -> close() synchronous and call event.preventDefault() on the listbox's mousedown event so option clicks never blur the input in the first place.

Follow-up questions

Similar questions

More Waymo interview questions

All 90 Waymo questions →