Create Javascript Fetch(), But with Timeout

RajRaj
3 min read

Table of contents

Hello Devs,

We want to fetch data from a particular URL and show it in the console. But if the URL is taking so long or taking longer time than the user-specified time, It will get automatically aborted.

So that is the problem statement, let's see how to conquer it.

Goal:

  • We want a function that accepts a "URL" & "Time" as a Parameter and like fetch(), and returns a Promise.

  •   const fetchWithTimeOut = (url, time) => {
        return new Promise((resolve, reject) => {
        });
      };
    
  • Then we call the normal fetch call, which we usually do most of the time .

  •    const fetchWithTimeOut = (url, time) = >{
        return new Promise((resolve, reject) = >{
      // Writing normal fetch method
          fetch(url).then((resp) = >{
    
            clearTimeout(timeId);
            return resp.json();
    
          }).then((data) = >{
    
            resolve(data);
    
          }).
          catch((e) = >{
            reject(e);
          });
        });
      };
    
  • But you will ask me, It's okay but how we will control it on the basis of time ? Here comes the "Hero of the movie" AbortController();

    The AbortController is used to provide a way to abort a network request created using the fetch .

  • Creation of the AbortController instance:

      const controller = new AbortController();
    
  • Here, an AbortController instance is created. An AbortController is an object that allows you to associate an AbortSignal with it, which can be used to send an abort signal to one or more DOM requests, such as a fetch request.

  •   const signal = controller.signal;
    

    The signal property of the AbortController object is used to get the associated AbortSignal. The AbortSignal is a signal object that can be used to abort one or more DOM requests, such as a fetch request.

  •   fetch(url, { signal })
        .then((resp) => {
          clearTimeout(timeId);
          return resp.json();
        })
        .then((data) => {
          resolve(data);
        })
        .catch((e) => {
          reject(e);
        });
    
  • When making a fetch request, you can pass the AbortSignal as an option in the request configuration. This associates the AbortController with the network request. If an abort signal is sent to the AbortController (e.g., by calling controller.abort()), it will cancel the network request, and any pending promises related to that request will be rejected.

  • A timer is set using, which will call controller.abort() after a specified time interval. If the network request doesn't complete within this timeout period, the controller.abort() function is called, which sends an abort signal to the associated fetch request. This effectively cancels the request.

  •   timeId = setTimeout(() => {
        controller.abort();
      }, time);
    

Full Code :

const fetchWithTimeOut = (url, time) => {
  return new Promise((resolve, reject) => {
    let timeId;
    const controller = new AbortController();

    const signal = controller.signal;

    fetch(url, { signal })
      .then((resp) => {
        clearTimeout(timeId);
        return resp.json();
      })
      .then((data) => {
        resolve(data);
      })
      .catch((e) => {
        reject(e);
      });

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

fetchWithTimeOut("https://jsonplaceholder.typicode.com/todos/1", 100)
  .then((resp) => {
    console.log(resp);
  })
  .catch((e) => {
    console.log(e);
  });
1
Subscribe to my newsletter

Read articles from Raj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Raj
Raj