Search code examples
javascriptajaxfetch-api

Fetch API request timeout?


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?


Solution

  • Edit 1

    As pointed out in comments, the code in the original answer keeps running the timer even after the promise is resolved/rejected.

    The code below fixes that issue.

    function timeout(ms, promise) {
      return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
          reject(new Error('TIMEOUT'))
        }, ms)
    
        promise
          .then(value => {
            clearTimeout(timer)
            resolve(value)
          })
          .catch(reason => {
            clearTimeout(timer)
            reject(reason)
          })
      })
    }
    
    

    Original answer

    It doesn't have a specified default; the specification doesn't discuss timeouts at all.

    You can implement your own timeout wrapper for promises in general:

    // Rough implementation. Untested.
    function timeout(ms, promise) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(new Error("timeout"))
        }, ms)
        promise.then(resolve, reject)
      })
    }
    
    timeout(1000, fetch('/hello')).then(function(response) {
      // process response
    }).catch(function(error) {
      // might be a timeout error
    })
    

    As described in https://github.com/github/fetch/issues/175 Comment by https://github.com/mislav