Fetch API request timeout?

Akshay Lokur picture Akshay Lokur · Oct 26, 2017 · Viewed 120.6k times · Source

I have a fetch-api POST request:

fetch(url, {
  method: 'POST',
  body: formData,
  credentials: 'include'
})

I want to know what is the default timeout for this? and how can we set it to a particular value like 3 seconds or indefinite seconds?

Answer

Karl Adler picture Karl Adler · Apr 16, 2018

I really like the clean approach from this gist using Promise.race

fetchWithTimeout.js

export default function (url, options, timeout = 7000) {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}

main.js

import fetch from './fetchWithTimeout'

// call as usual or with timeout as 3rd argument

fetch('http://google.com', options, 5000) // throw after max 5 seconds timeout error
.then((result) => {
    // handle result
})
.catch((e) => {
    // handle errors and timeout error
})