DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at on


Timeout with Fetch API

Setting up a timeout for HTTP requests can prevent the connection from hanging forever, waiting for the response. It can be set on the client side to improve user experience, and on the server side to improve inter-service communication. Fetch API is fully available in Node as well from version 18.

AbortController can be utilized to set up timeouts. Instantiated abort controller has a signal property which represents reference to its associated AbortSignal object. Abort signal object is used as a signal parameter in the request with Fetch API, so HTTP request is aborted when abort method is called.

const HTTP_TIMEOUT = 3000;
const URL = '';

(async () => {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), HTTP_TIMEOUT);

  try {
    const response = await fetch(URL, {
      signal: controller.signal
    }).then((res) => res.json());
  } catch (error) {
  } finally {
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

_bkeren profile image
zsevic profile image
Željko Šević

I updated the article with AbortController reference, thanks

Sending data via light 🤯

... with JavaScript 🤯 🤯🤯

Using visible light, data can be encoded and transmitted using a technology called Li-Fi which aims at using your existing lights for wireless communication.

Sending data via light

Read more