Why Is There No Timeout Parameter for Fetch?

Fetch doesn't include a built-in timeout feature, but you can find articles on internet that shows you how to add it using about 20 lines of code.

The question arises: Why doesn't ES6 Fetch include timeouts by default? Having a timeout seems like a basic and necessary feature, crucial for preventing a request from hanging indefinitely.

There must be a good reason this wasn't implemented, and developers have had to create workarounds. Let me explain why.

The lack of a built-in timeout feature in the Fetch API has been a point of discussion and concern within the developer community. This GitHub issue contains a lengthy discussion on this topic.

The Fetch API was designed to be minimalistic and to closely resemble the underlying HTTP semantics. The decision not to include a built-in timeout in the Fetch API was intentional, and there are a few reasons behind it:

  • Timeouts Can Be Complex: Implementing timeouts in a way that satisfies all potential use cases can be more complex than it might seem at first. For example, what should happen if a timeout occurs during the process of establishing a connection? Should it be considered a network error or something else?

  • Flexibility for Developers: The designers of the Fetch API aimed to provide a simple and flexible interface. Adding timeouts might introduce additional complexity and make the API less straightforward. Instead, developers are expected to handle timeouts in a way that best fits their specific requirements.

  • Use of AbortController: While the Fetch API itself doesn't have a built-in timeout, the AbortController interface, introduced in the same ECMAScript version (ES6/ES2015), can be used to implement timeouts. By creating an AbortController and associating its signal with the fetch request, you can later call abort() on the controller to cancel the request after a certain period, effectively creating a timeout.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda