Skip to the solution
MediumFrontend7 min read

Implement a Debounced Search Input With Race-Condition-Safe Request Cancellation

349 views

The problem

Problem, as an interviewer would state it: "Build a search-as-you-type controller: debounce the input, fire a real API request, and correctly handle the case where an EARLIER request resolves AFTER a LATER one — the UI must always show the result matching the user's most recent input, not whichever request happens to finish first."

Examples:

Code
controller.search("reactjs"); // a slow request
controller.search("react");   // a fast request, made moments later
// even if "reactjs" resolves AFTER "react" does, the displayed result is for "react"

Clarifying questions expected:

  • Is debouncing alone (only firing the LAST call in a burst) enough, or is a separate race-condition guard also needed?
  • Should a discarded, stale response still be silently ignored, or surfaced somehow (e.g., logged)?
  • Would using AbortController to genuinely CANCEL the stale network request be preferable to just ignoring its result?

Code / implementation expected: Yes — real, direct proof with a deliberately adversarial timing setup where the earlier request is slower and the later request is faster.

  • debounce
  • async
  • race-condition
  • fetch

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: an earlier, slower request that resolves after a later, faster one is correctly discarded by the race-condition guard

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 117 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Partition Array

Continue