fetch() with timeout

Being from early JavaScript days, you might’ve been used to setting a timeout for all your HTTP requests in jQuery or libraries like axios, request, etc. Yet to your surprise, there’s no timeout parameter for native browser’s fetch.

However, the way fetch extends on this, is now it allows you to set a different condition to abort the request. This can be not only the timeout, but any other condition (i.e. user logs out of the system, and all pending requests have to be halted immediately). It is possible with the special signal parameter, that accepts an AbortSignal object from the AbortController. Here’s how:

const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => {
  controller.abort();
}, 30000);

fetch('https://example.com', { signal })
  .then(response => response.json())
  .then(data => {
    // Do something with the data
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Fetch request timed out');
    } else {
      console.log('Fetch request failed:', error);
    }
  });

You will notice the signal parameter we passed to the fetch function, which will abort the request as soon as the controller is aborted. If you want to support very old browsers like Internet Explorer and legacy Edge, then you need to add a polyfill to your application. Via npm or via a <script> inclusion:

npm install --save abortcontroller-polyfill
<script src="https://unpkg.com/abortcontroller-polyfill/dist/abortcontroller-polyfill.umd.js"></script>

Resources


Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

Your email address will not be published. Required fields are marked *