Timeout with the fetch API
decker
Posted on August 20, 2022
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>)
to your fetch like in this example and you are done — at least for the timeout.
fetch(<url>, {
...
signal: AbortSignal.timeout(5000)
})
Hope this helps to get more comfortable with the fetch API.
💖 💪 🙅 🚩
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.