Timeout with the fetch API

decker67

decker

Posted on August 20, 2022

Timeout with the fetch API

Some time ago I shifted from Axios to fetch, to get rid of another dependency. Nowadays the fetch API is available everywhere, in the browser and also in node, so no need to take something else and it also supports streaming that is not available in Axios.

But when it comes to set a timeout for a request, how could this be done?

I saw solutions using setTimeout but far better seems the following solution.

Simply add

signal: AbortSignal.timeout(<number>)
Enter fullscreen mode Exit fullscreen mode

to your fetch like in this example and you are done — at least for the timeout.

fetch(<url>, {
  ...
  signal: AbortSignal.timeout(5000)
})
Enter fullscreen mode Exit fullscreen mode

Hope this helps to get more comfortable with the fetch API.

💖 💪 🙅 🚩
decker67
decker

Posted on August 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Timeout with the fetch API
fetch Timeout with the fetch API

August 20, 2022