Abort Fetch API Request

Here's how to abort a fetch based on a timeout.

Sometimes you want to stop a fetch request mid request. Perhaps, for instances, there's not a timeout on the backend server. You could be fetching... forever.

There's not a timeout option to pass to fetch. Instead, you get to light up the "fetch signal":

The signal is an option to the fetch api (2nd arg):

An AbortSignal object instance; allows you to communicate with a fetch request and abort it if desired via an AbortController.

As the docs say, the signal will come from an AbortController. Instantiate one of those, pass the signal to the fetch, then call abort, and the fetch is stopped short.

This will start and immediately stop the fetch:

const controller = new AbortController()
const response = await fetch('https://swapi.dev/api/people/1', {
  signal: controller.signal,
})
controller.abort()

If you wanted to make a request and then abort based on a timeout, say 5 seconds, you can do that too:

const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), 5000)
const response = await fetch('https://swapi.dev/api/people/1', {
  signal: controller.signal,
})
clearTimeout(timer)

If your request comes back before the 5 second mark, the timer is cleared, and it won't abort. Otherwise, it's goooooooone.