Skip to curriculum
Jump to the editor

14.2. Fetch with a timeout and cancellation

Medium
Topics
20–30 min

fetch has no time limit of its own. On a bad mobile connection a request can hang for minutes while the page shows a spinner. Rejecting a wrapper promise after a while is not enough either: the request keeps running and keeps the connection busy. The fix is to abort it, with an AbortController, and to let the caller cancel it too (the user leaves the page, a newer search replaces this one).

Write fetchWithTimeout(url, options) in fetch-with-timeout.js. It calls fetch and aborts the request when options.timeout milliseconds pass, or when the caller's options.signal aborts, whichever comes first.

Signature

JAVASCRIPT
function fetchWithTimeout(url, options) // returns a Promise of a Response
  • url: passed to fetch unchanged.
  • options: optional. Every option fetch knows (method, headers, body…) is passed on, plus two of your own:
    • timeout: the time limit in ms. Missing means no time limit.
    • signal: an AbortSignal from the caller. Aborting it cancels the request.
  • Returns the promise of fetch's response, or a rejection.

Requirements

  1. fetch is called once, at once, with url, every other option, and an AbortSignal of your own. timeout is not passed to fetch.
  2. A response that arrives in time is the result.
  3. When timeout ms pass first (exactly then, not earlier), the request is aborted and the result rejects with a DOMException named "TimeoutError".
  4. Without timeout, no timer is started and the request may take as long as it takes.
  5. When the caller's signal aborts, the request is aborted and the result rejects with the signal's own reason.
  6. If signal has already aborted, fetch is not called and the result rejects with signal.reason.
  7. A time-out never aborts the caller's signal.
  8. When the request settles (response, error or abort), the timer is cleared and the listener on the caller's signal is removed. Aborting after the response changes nothing.
  9. An error from fetch, including one thrown at once, comes back unchanged as a rejection.
  10. Each call has its own controller and timer.

Examples

JAVASCRIPT
const response = await fetchWithTimeout("/api/user", { timeout: 3000 });
// the response, if it arrives within 3 s
JAVASCRIPT
try {
  await fetchWithTimeout("/api/report", { timeout: 2000 }); // the server takes 10 s
} catch (error) {
  console.log(error.name); // "TimeoutError", at 2000 ms; the request is aborted
}
JAVASCRIPT
const controller = new AbortController();
const request = fetchWithTimeout("/api/search?q=re", { timeout: 5000, signal: controller.signal });
controller.abort();
request.catch((error) => console.log(error.name)); // "AbortError": the caller's reason
JAVASCRIPT
fetchWithTimeout("/api/post", { method: "POST", body: "{}", timeout: 1000 });
// fetch("/api/post", { method: "POST", body: "{}", signal: <your signal> })

Environment

  • Plain JavaScript in a browser page; the tests call the global fetchWithTimeout from fetch-with-timeout.js.
  • The page has no network: each test puts in a fake fetch that answers after a delay and, like the real one, rejects with signal.reason when its signal aborts.
  • The tests run on a virtual clock that replaces setTimeout and clearTimeout. AbortSignal.timeout uses the browser's own timers, which the clock cannot move, so use setTimeout.
  • Time spent reading the body after the response arrives is not part of this problem.

Hints

  1. controller.abort(reason) takes a reason. What does the promise from fetch reject with when its signal aborts?
  2. The abort event fires once, when a signal aborts. What if it aborted before you started listening?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…