Timeout with the fetch API
decker

decker @decker67

Joined:
May 27, 2022

Timeout with the fetch API

Publish Date: Aug 20 '22
2 0

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.

Comments 0 total

    Add comment