Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Async Patterns for Requests

Cancelling Requests and Timeouts

Cancel fetch requests with AbortController, add timeouts with AbortSignal.timeout, combine signals with any(), and stop stale search results from winning.

Starting a request is easy. Knowing when to stop one is the harder half. A user navigates away, a server hangs for a minute, or someone types a new search term while the old search is still loading. If you do nothing, the old request keeps using bandwidth, and worse, its late response may overwrite newer data on the screen.

The browser's answer is the abort signal: you create a controller, hand its signal to fetch(), and call abort() when you no longer want the answer. This lesson covers cancelling by hand, timeouts, combining several reasons to cancel, and the race condition that makes cancellation matter in real interfaces. See also the AbortController reference.

How AbortController works

An AbortController has two parts: a signal you pass to the work, and an abort() method you call to cancel it. Real fetch() accepts { signal } and rejects its promise with an error named AbortError when the signal aborts.

sequenceDiagram
    participant C as Your code
    participant F as fetch
    C->>C: controller = new AbortController()
    C->>F: fetch(url, { signal })
    Note over F: request in flight
    C->>C: controller.abort()
    F-->>C: promise rejects with AbortError

Calling abort() makes the pending fetch promise reject with an AbortError.

To run this in the sandbox without a server, the examples use a small slowRequest() function that behaves like fetch: it waits, then resolves, but listens to the signal and rejects with the same kind of error if it is aborted. Real code just calls fetch(url, { signal }).

JS Cancelling a request by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

By default, abort() makes the rejection an AbortError with the message "This operation was aborted". You can pass your own reason, controller.abort(new Error("Page closed")), and it appears as signal.reason. A signal can only abort once, and it cannot be reused: create a new controller for every request or group of requests.

Cancelling is not a failure the user should see. A typical catch ignores it:

JavaScript
try {
  const response = await fetch(url, { signal });
  return await response.json();
} catch (error) {
  if (error.name === "AbortError") {
    return null;
  }
  throw error;
}

Timeouts with AbortSignal.timeout

Without a timeout, fetch() can wait for a very long time. Modern browsers give you a ready-made signal: AbortSignal.timeout(ms) aborts by itself after the delay. The rejection is a TimeoutError, which lets you tell a timeout apart from a user cancel.

JS AbortSignal.timeout and the TimeoutError

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare this with building a timeout from setTimeout() plus controller.abort(): you must also clear the timer when the request finishes first, or it keeps running. AbortSignal.timeout() has no such cleanup.

Combining signals with AbortSignal.any

Often a request should stop for several reasons: the user clicked Cancel, or the time limit ran out. AbortSignal.any([a, b]) returns a signal that aborts as soon as any listed signal does, and it carries that signal's reason.

JS One signal, two reasons to stop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Browsers have supported AbortSignal.timeout() and AbortSignal.any() since 2022 to 2024, so they are safe in current versions; very old browsers need the manual setTimeout approach.

Cancelling stale requests

Here is the problem that makes cancellation essential. A user types a, then quickly ab. Request 1 (a) is slow, request 2 (ab) is fast. The responses arrive in the wrong order, and the older answer replaces the correct one. The results list now shows matches for a while the input contains ab.

sequenceDiagram
    participant U as User
    participant P as Page
    participant S as Server
    U->>P: types "a"
    P->>S: search "a" (slow)
    U->>P: types "ab"
    P->>S: search "ab" (fast)
    S-->>P: results for "ab"
    S-->>P: results for "a" (late, wrong)

Out-of-order responses: the old request finishes last and overwrites the correct result.

The fix is to keep one controller per search and abort the previous one before starting a new one. This TryIt first shows the bug, then the fix.

JS Fixing out-of-order results

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without cancelling, the list ends on the stale results for a. With cancelling, the first request is aborted when the second one starts, and only the latest result is shown. Even when the server cannot stop working, ignoring the aborted promise makes your UI correct. You will use this exact pattern again in Live Search, Pagination and Infinite Scroll.

Aborting does not undo work the server has already done. If a POST was already received, cancelling in the browser does not stop the server from saving the data. Use cancellation for reading, and treat cancelled writes as "outcome unknown".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does fetch do when the signal you passed is aborted?

    An aborted fetch rejects. The default reason is a DOMException named AbortError, or whatever reason you passed to abort().
  2. 2. How can you tell a timeout from a manual cancel?

    AbortSignal.timeout() aborts with a TimeoutError, whereas controller.abort() uses AbortError unless you supply another reason.
  3. 3. You want a request to stop when the user clicks Cancel or after 5 seconds, whichever comes first. What do you use?

    AbortSignal.any combines signals into one that aborts as soon as any input aborts.
  4. 4. Why abort the previous search request when the user types again?

    Responses can arrive out of order. Aborting (or ignoring) the older request guarantees that only the latest one updates the page.

Summary

  • Pass { signal } from an AbortController to fetch(); abort() makes the promise reject with AbortError.
  • A controller works once; make a new one for every request.
  • AbortSignal.timeout(ms) gives timeouts that reject with TimeoutError, and AbortSignal.any() merges several reasons to cancel.
  • Abort the previous request when a new one replaces it, so stale responses never reach the screen.
  • Cancelling a write does not guarantee the server did not process it.

Next: Retries, Backoff and Resilience.