DEV Community

Cover image for Timeout with the fetch API
decker
decker

Posted on

2

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.

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay