How to set request timeout with Fetch API?

Sometimes, we want to set request timeout with Fetch API.

In this article, we’ll look at how to set request timeout with Fetch API.

How to set request timeout with Fetch API?

To set request timeout with Fetch API, we can use the AbortController constructor.

For instance, we write

const controller = new AbortController();

const timeoutId = setTimeout(() => controller.abort(), 5000);

const req = async () => {
  const response = await fetch(url, { signal: controller.signal });
  //...
  clearTimeout(timeoutId);
};
req();

to create an AbortController object.

Then we call abort in the setTimeout function to cancel the request that’s been assigned the abort controller signal object after 5 seconds.

Then we call fetch with the url to make the request to and the signal property of the object in the 2nd argument is set to controller.signal.

Assigning signal to controller.signal lets us abort the request with controller.abort.

After the request is done, we call clearTimeout with the timeoutId to cancel the setTimeout timer.

If the timer is cancelled after 5 seconds, then abort runs and the request will be cancelled.

Conclusion

To set request timeout with Fetch API, we can use the AbortController constructor.