Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Cancel and time out fetch requests

Set your own fetch deadline with AbortSignal.timeout or cancel an in-flight request with AbortController.

Your script calls fetch, the server accepts the connection, and then it says nothing. The script waits. Without a signal, you have no application-level deadline. The runtime or network can still end the request.

To test this I wrote a small server on port 4200 that answers every request after five seconds. Every example below calls it.

// server.mjs
import { createServer } from 'node:http'

createServer((req, res) => {
  setTimeout(() => res.end('{"ok":true}'), 5000)
}).listen(4200, '127.0.0.1')

Start it with node server.mjs in one terminal and run the other scripts from a second terminal. Each script is saved under the name in its first comment.

Give fetch a timeout

Pass a signal made by AbortSignal.timeout() in the options. It takes a number of milliseconds and returns a signal that aborts after that time.

// timeout.mjs
try {
  const res = await fetch('http://127.0.0.1:4200/report', {
    signal: AbortSignal.timeout(2000),
  })
  console.log(await res.json())
} catch (err) {
  if (err.name === 'TimeoutError') {
    console.log('Timed out after 2 seconds')
  } else {
    throw err
  }
}

Run node timeout.mjs and it prints Timed out after 2 seconds.

The error is a DOMException named TimeoutError, per MDN. Check err.name and rethrow everything else, so a real network failure is not reported as a slow server.

Cancel it yourself

A timeout is a cancel you do not have to call. When you want to cancel on a user action, such as a closed panel or a new search, create an AbortController and pass its signal.

// cancel.mjs
const controller = new AbortController()

const request = fetch('http://127.0.0.1:4200/report', {
  signal: controller.signal,
})

setTimeout(() => controller.abort(), 500)

try {
  await request
} catch (err) {
  console.log(err.name) // AbortError
}

This prints AbortError after about half a second, long before the server answers.

For these examples, TimeoutError means the timeout signal expired and AbortError comes from calling abort() without a reason. Network failures can still throw other errors.

In a catch block, branch on err.name. Show "try again" for a timeout and ignore the abort you asked for.

An aborted signal stays aborted. Create a fresh signal for a new cancellation scope. You can share one signal across requests you want to cancel together.

Use Node 18 or newer to run these examples without a flag.

April 2024 update: AbortSignal.timeout() is now available across current browser engines. In browsers the timeout measures active time, so it pauses while the page is in the back-forward cache.