fetch with Timeout

By  on  

A few years back I wrote a blog post about how write a fetch Promise that times out. The function was effective but the code wasn't great, mostly because AbortController , which allows you to cancel a fetch Promise, did not yet exist. With AbortController and AbortSignal available, let's create a better JavaScript function for fetching with a timeout:

AbortSignal instances now feature a timeout option to time the Promise out after a given amount of milliseconds:

async function fetchWithTimeout(url, opts = {}, timeout = 5000) {
  // Create a signal with timeout
  const signal = AbortSignal.timeout(timeout);

  // Make the fetch request
  const _fetchPromise = fetch(url, {
    ...opts,
    signal,
  });

  // Await the fetch with a catch in case it's aborted which signals an error
  const result = await _fetchPromise;
  return result;
};

// Usage
try {
  const impatientFetch = await fetchWithTimeout('/', {}, 2000);
}
catch(e) {
  console.log("fetch possibly canceled!", e);
}

While formerly the AbortSignal would come from an AbortController, you can now use AbortSignal.timeout to create the signal.

At the moment, however, only edge browser versions support AbortSignal.timeout. So much like the original function, an alternative function could use setTimeout to time to the cancellation but we'll use the signal with the fetch request:

async function fetchWithTimeout(url, opts = {}, timeout = 5000) {
  // Create the AbortController instance, get AbortSignal
  const abortController = new AbortController();
  const { signal } = abortController;

  // Make the fetch request
  const _fetchPromise = fetch(url, {
    ...opts,
    signal,
  });

  // Start the timer
  const timer = setTimeout(() => abortController.abort(), timeout);

  // Await the fetch with a catch in case it's aborted which signals an error
  try {
    const result = await _fetchPromise;
    clearTimeout(timer);
    return result;
  } catch (e) {
    clearTimeout(timer);
    throw e;
  }
};

// Usage
try {
  const impatientFetch = await fetchWithTimeout('/', {}, 2000);
}
catch(e) {
  console.log("fetch possibly canceled!", e);
}

The JavaScript code above is much cleaner now that we have a proper API to cancel fetch Promise calls. Attaching the signal to the fetch request allows us to use a setTimeout with abort to cancel the request after a given amount of time.

It's been excellent seeing AbortController, AbortSignal, and fetch evolve to make async requests more controllable without drastically changing the API.

Recent Features

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    9 More Mind-Blowing WebGL Demos

    With Firefox OS, asm.js, and the push for browser performance improvements, canvas and WebGL technologies are opening a world of possibilities.  I featured 9 Mind-Blowing Canvas Demos and then took it up a level with 9 Mind-Blowing WebGL Demos, but I want to outdo...

Incredible Demos

  • By
    CSS Fixed Positioning

    When you want to keep an element in the same spot in the viewport no matter where on the page the user is, CSS's fixed-positioning functionality is what you need. The CSS Above we set our element 2% from both the top and right hand side of the...

  • By
    Create a NoScript Compatible Select Form Element with an onChange Event

    I wouldn't say that I'm addicted to checking Google Analytics but I do check my statistics often. I guess hoping for a huge burst of traffic from some unknown source. Anyway, I have multiple sites set up within my account. The way to...

Discussion

  1. Bas

    Can’t you do the clearTimeout(timer); in a finally block? Instead of both in the regular flow and the catch.

  2. Chris

    There’s also AbortSignal.timeout(). I think it’s about as well supported as signal by now, but pretty easy to shim.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!