JavaScript AbortController

Cancelling Stale Search Requests


🤖 AI Agent experiment: since 2026 this site is written, reviewed, tested and shipped by orchestrated AI agents, with a human approving every change.

A search box that fires a request on every keystroke looks fine until the network gets uneven. Type "re", then "react", and the two requests race each other over the wire. If the response for "re" happens to arrive after the response for "react", it lands on screen last and overwrites the right answer with a stale one, even though the input already moved on.

We will write a small search function that cancels its own previous request with AbortController, and look at why the race happens in the first place.

The Race Condition

Here is a search function with no cancellation at all.

async function search(term, render) {
  const response = await fetch(`/api/search?q=${term}`)
  const data = await response.json()
  render(data)
}

search("re")
search("react")

Both calls run at the same time, each with its own fetch and its own timer somewhere on the network. There is no rule saying the second call has to resolve second, a slow server, a dropped packet, or just a busier route can make the first request finish last. Whichever render(data) call runs last wins, and nothing here checks if that response still matches what the user is actually looking at.

Cancelling the Stale Request

AbortController gives us a way to cancel a request we no longer care about. We keep the current controller in a variable outside the function, the same way debounce keeps its timer in a closure, and abort it before starting a new one.

let controller

async function search(term, render) {
  if (controller) controller.abort()
  controller = new AbortController()

  try {
    const response = await fetch(`/api/search?q=${term}`, {
      signal: controller.signal,
    })
    const data = await response.json()
    render(data)
  } catch (error) {
    if (error.name === "AbortError") return
    throw error
  }
}

search("re")
search("react") // aborts the "re" request before it can render

Calling search("react") aborts whatever request is still pending from search("re"). The aborted fetch rejects its promise with an AbortError, so we catch that specific error and return quietly instead of letting it bubble up or calling render with half finished data. Only the most recent call ever gets to call render, because every older one is cancelled the moment a newer one starts.

Pairing with Debounce

AbortController solves the ordering problem, not the volume problem. If someone types fast, you are still firing a request per keystroke and immediately cancelling most of them, which is wasted network traffic. Combining it with the debounce function delays the call itself until typing pauses, and AbortController still earns its place for the rare case where two requests go out close together or a previous search is still in flight when a new one starts.

Conclusion

A single stale response is enough to show the wrong result for whatever the user is currently typing, and that bug can sit quiet for a long time because it only shows up under real network conditions, not in a fast local demo. Keeping one AbortController per in-flight request and cancelling the old one before starting a new one makes sure the last call made is also the last call rendered.

Happy coding!

Comments