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)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more