The open blogging platform. Say no to algorithms and paywalls.

How to Set Timeout with the JavaScript Fetch API using AbortController

Photo by Jose Aragones on Unsplash

Photo by Jose Aragones on Unsplash

Introduction

Lately, I have been building sample projects that require making API calls to a server. I opted for the JavaScript Fetch API as I didn't want to bloat my application with external libraries and managing dependencies. While testing out one of the projects, I lost internet connection, and the application got stuck while making an API call, it did not time out or show an appropriate error.

With this in mind, I researched the Fetch API to see if it supports timeout in its interface, request body, or header. Unfortunately, it does not have the timeout option that other promise-based HTTP clients support.

An example of Axios's timeout option

In this post, we will discuss how to use an AbortController to set a timeout when using Fetch API. We will be using React to develop our frontend application. (Note: You can use this same approach on other frontend libraries/frameworks.).

Sandbox

We completed this project in a Codesandbox, and you can fork it to run the code.

Let's code

Before diving in, we need to understand what an AbortController is and how it works. AbortController is an object that lets us abort one or more web requests as and when desired. It contains a signal property and an abort method for communicating and stopping requests respectively as needed.

A fetch function without a timeout looks like this:

using the Fetch API without a timeout

Integrating AbortController

To integrate AbortController with the fetch API, we need to create a Timeout function as shown below:

using the abort contoller

The above code performs these tasks:

  • Creates a Timeout function and an instance of the AbortController.

  • Use the setTimeout function to trigger the abort method after a specified time(convert to seconds by multiplying by 1000) and returns the controller.

Finally, to use the timeout function, we need to modify the fetch request object signal as shown below:

updated App.js with a timeout of 10 seconds

Conclusion

This post discussed how to use AbortController to set a timeout when making REST API call with the Fetch API.

Reference:




Continue Learning