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:
AbortSignal&AbortControllerAbortSignal()initializesself.aborted = False.AbortController()createsself.signal = AbortSignal(), andabort() -> Noneflipsself.signal.aborted = True.
Autocomplete(fetch_suggestions, delay_ms=300, list_id="ac-listbox")on_input(value: str, now_ms: int) -> None: Record rawvalue, clear any keyboard highlight, cancel any pending debounce timer, and examinequery = value.strip().- If
query == ""(empty or whitespace-only), immediately abort any active network call, clear cached suggestions, collapse the listbox, and setstatus = "idle". - Otherwise schedule
queryto be fetched once the clock reachesnow_ms + delay_ms.
- If
advance_to(now_ms: int) -> None: Advance logical time (milliseconds). Whenever a debounce timer is pending andnow_ms >= timer_due, clear the timer, abort any still-active earlier request, create a freshAbortController, setstatus = "loading", and invokefetch_suggestions(query, controller.signal).on_response(signal: AbortSignal, items: List[str]) -> bool: Processitemsonly ifsignalbelongs to the single currently active request; returnFalsewithout changing UI state if stale or cancelled. When current, clear the active controller, storeitemslinked to that request's trimmed query, clear keyboard highlight, setstatus = "ready"and expand the popup whenitemsis non-empty (or setstatus = "empty"and collapse the popup whenitemsis empty), and returnTrue.on_error(signal: AbortSignal, message: str) -> bool: Process the failure only ifsignalbelongs to the currently active request (silently returningFalsefor aborted or superseded requests). When current, clear the active controller, clear options, collapse the popup, clear highlight, setstatus = "error", and returnTrue.on_keydown(key: str) -> Optional[str]:"ArrowDown"/"ArrowUp": If no options are stored, returnNone. When collapsed, reopen (0for"ArrowDown",len(options) - 1for"ArrowUp") only if the stored options matchvalue.strip(); otherwise stay collapsed and returnNone. When already expanded, cycle the highlight with wrap-around (if expanded with no option highlighted yet,"ArrowDown"highlights0and"ArrowUp"highlightslen(options) - 1). ReturnNone."Enter": If expanded with an active highlight, select that option and return its text; otherwise returnNone."Escape": Callclose()and returnNone.
select(index: int) -> str: Setvalue = options[index], callclose()without scheduling a new search, and return the chosen string.on_blur() -> None: Callclose().close() -> None: Cancel any pending timer, abort any active request, collapse the popup, clear highlight, and setstatus = "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_inputandadvance_toare non-decreasing integer milliseconds. - Leading and trailing whitespace in
valueis stripped before deciding whether a query is blank or passing it tofetch_suggestions, whilerender()["value"]preserves the exactvaluestring typed or selected. fetch_suggestionsmay invokeon_responseoron_errorin any order, or ignoresignal.aborted.
Step-by-step walkthrough
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:
- Text edits (
on_input), - Timer ticks (
advance_to), - Out-of-order network callbacks or errors (
on_response,on_error), - 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 afterEscape— 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 dictclass 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 = TrueInside
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 inself.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- Text edits (
Coalesce rapid typing with debouncing and handle blank input
Debouncing delays firing a request until
delay_msof quiet time have elapsed since the latest edit. Whenever another keystroke arrives beforetimer_due, we replace the deadline withnow_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_inputprevent subtle bugs:- Reset
self.active = -1on every edit: if the user highlighted row1from an earlier list and typed another character, pressingEntermust 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)- Reset
Eliminate network races with cancellation plus signal identity
When
"py"launches at300 msand"pyt"launches at700 ms, the slower"py"response can arrive after"pyt"has already rendered. We guard against stale updates at two levels:- Active cancellation (
abort()):_start_requestaborts the previousAbortControllerbefore creating a new one, flippingold_signal.aborted = Trueso HTTP clients can drop the obsolete socket. - Signal identity check (
_is_current): even if a caller ignoressignal.aborted,self.controller is not None and self.controller.signal is signalguarantees that only the single active request can mutateoptionsorstatus.
The same
_is_current(signal)guard insideon_errorsilently dropsAbortErrorrejections 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- Active cancellation (
Close cleanly on Escape, blur, and selection
Pressing
Escape, blurring the input (on_blur), and selecting an item (select) all shareclose(), which clearstimer_dueand abortscontrollerso no late response can reopen a dismissed popup.select(index)copiesself.options[index]intoself.valueand callsclose()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"Navigate with arrow keys and render WAI-ARIA combobox attributes
In a WAI-ARIA combobox, DOM focus remains inside the text input while
aria-activedescendantpoints to theidof the highlighted option (aria-selected="true"). Two keyboard subtleties matter inon_keydown:- Reopening a dismissed popup: pressing
ArrowDownorArrowUpwhile collapsed reopens cachedself.optionsonly ifself.options_query == self.value.strip()(blocking stale"py"items if the user typed"pyt"and pressedEscape). - Initial
ArrowUpwhenself.active == -1: right after options arrive,activeis-1. Checkingelif self.active <= 0: self.active = n - 1cleanly sends bothactive == -1(freshly opened list) andactive == 0(wrap-around from the top) ton - 1(whereas(-1 - 1) % nwould mistakenly jump ton - 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 -> 1def 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- Reopening a dismissed popup: pressing
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)returnsFalse, keeping["python", "pytest"]intact.Equivalent browser JavaScript wiring
Every field of the Python state machine maps directly onto browser DOM APIs:
timer_duemaps toclearTimeout(timerId)+setTimeout(..., delayMs);_is_current(signal)maps tocontroller === currentControllerinside.then()and.catch();- Calling
event.preventDefault()on the listbox'smousedownevent keeps focus inside the<input>so clicking an option is not swallowed byblur; - Writing
item.textContent = options[i](neverinnerHTML) prevents cross-site scripting (XSS).
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):
t = 0 ms, user types"py":timer_duebecomes300; no network call yet.t = 300 ms, timer fires:c1 = AbortController()becomesself.controller, startingfetch_suggestions("py", c1.signal).t = 400 ms, user types"pyt":timer_dueadvances to700andactiveresets to-1.t = 700 ms, timer fires:c1.abort()cancels"py",c2 = AbortController()replacesself.controller, andfetch_suggestions("pyt", c2.signal)starts.t = 740 ms(c2resolves) thent = 780 ms(c1resolves late):c2.signalmatchesself.controller.signal, rendering["python", "pytest"]and clearingself.controller = None;40 mslaterc1.signalfails_is_currentand is ignored.
Complexity
- Time:
O(1)per input edit, clock advance, or key press, andO(n)per network response orrender(), wherenis the number of returned suggestions. Updatingtimer_due, abortingcontroller, and cyclingself.activetouch a constant number of scalar fields, whileon_responseandrenderloop once across thenvisible options. Across a burst ofkkeystrokes spaced closer thandelay_ms, debouncing collapseskedits into1network call. - Space:
O(n). State holds only the current list ofnsuggestion strings, scalar status fields, one timer deadline, and at most one activeAbortController.
Edge cases
- Out-of-order stale response (
"py"arriving after"pyt"): blocked by_is_current(signal)via object identity (is), even iffetch_suggestionsignoressignal.aborted. AbortErrorrejection on cancelled requests: when_abort_request()aborts an olderAbortController,_is_current(old_signal)isFalse, keeping normal cancellations silent instead of flashing"Suggestions could not be loaded".- Cleared or whitespace-only input (
""or" "):on_inputstrips whitespace, cancels the timer, aborts any active request, emptiesoptions, and resetsstatus = "idle". - Empty suggestion list (
[]):expandedbecomesFalseandstatusbecomes"empty"with live-region message"No suggestions". ArrowUpon a freshly opened list (active == -1):self.active <= 0 -> n - 1highlights the bottom optionn - 1rather than miscomputing(-1 - 1) % n = n - 2.Escapeorblurmid-fetch followed byArrowDown:close()aborts the request, andon_keydownverifiesself.options_query == self.value.strip()before reopening so old"py"items cannot reopen under"pyt".Enterwith no highlighted row (active == -1): returnsNoneso standard form submission still works when submitting typed text directly.
Common mistakes
- "Last response wins" instead of "latest request wins": mutating
optionsunconditionally inside.then()lets slow earlier prefixes overwrite fast newer prefixes. - Skipping the signal identity check after
abort(): mocks or custom wrappers that resolve despitesignal.abortedwill still overwrite state unless you verifyself.controller.signal is signal. - Surfacing
AbortErroras a network failure: user-driven cancellation during typing is normal operation and must stay silent. - Confusing throttling with debouncing: throttling fires every
delay_msduring continuous typing, whereas debouncing waits until typing pauses fordelay_ms. - Losing mouse clicks on options to
blur: in browsers,mousedown->input.blur->mouseup->click; withoutevent.preventDefault()on listboxmousedown,blurhides the list beforeclickfires. - Rendering suggestions via
innerHTML: untrusted completion strings trigger cross-site scripting (XSS); always assigntextContent.
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
Mapby normalized query (query.trim().toLowerCase()) storing{ items, expiresAt }with a short TTL (time-to-live) such as60 s. Check the cache when the debounce timer fires: on a fresh hit, abort any active network call and apply the cacheditemsimmediately with zero network traffic; when a network call succeeds, storeitems(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 === trueon'input'and'keydown'events until'compositionend'fires. Ignore'input'events whileevent.isComposingistrue, invokeonInput()once inside'compositionend'with the committed characters, and skip comboboxkeydownhandling wheneverevent.isComposing || event.keyCode === 229soEnterand 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
blursynchronously callsclose(), clearingtimer_dueand abortingcontrollerso tabbing past the field never leaks timers or pops suggestions over neighboring inputs. AvoidsetTimeout(close, 200)workarounds onblur—a delayed blur timer races with rapid re-focusing and wipes out freshly typed queries; instead keepblur -> close()synchronous and callevent.preventDefault()on the listbox'smousedownevent so option clicks never blur the input in the first place.
Follow-up questions
- How can you add a client-side response cache so repeated prefixes do not trigger duplicate API calls?
- What adjustments are needed for CJK Input Method Editors (IME) so phonetic composition keystrokes do not fire premature searches or steal Enter/Arrow keys?
- How do you prevent race bugs and dropped option clicks when focus rapidly enters and leaves the input box?
Similar questions
- Interactive Naval Grid with Derived Ship Status
- Implement a Custom-Debounced Typeahead Search Controller
- Fix Stale Views and RxJS Memory Leaks in Angular
- External-Memory Deduplication of a Massive File
- Time-Ordered Ride Dispatch Scheduler
- Multi-Sensor Entity Observation Tracker
More Waymo interview questions
- Sensor Collection and Dispatch System for Mapping Fleets Medium
- Single-Source Shortest Distances to Query Nodes Medium
- Comparing Sparse Incident Rates Across Unequal Mileage Medium Pro
- Fix Stale Views and RxJS Memory Leaks in Angular Medium Pro
- Validate Fleet Dispatch Readiness From Service Logs Medium Pro
- Presenting a Demanding Engineering Project and Its Core Obstacles Medium Pro
- Walk Through Your Proudest Engineering Project Medium Pro
- Map-Collection Vehicle Fleet and Ingestion Platform Hard Pro
- Worldwide Low-Latency Cache for Small Image Assets Medium Pro
- Design an Online Matchmaker with Cancellations and Timeouts Medium Pro