<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Raj's Frontend DOJO]]></title><description><![CDATA[Raj's Frontend DOJO]]></description><link>https://raj-stark.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 03 Sep 2026 11:00:37 GMT</lastBuildDate><atom:link href="https://raj-stark.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Create Javascript Fetch(), But with Timeout]]></title><description><![CDATA[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 ho...]]></description><link>https://raj-stark.hashnode.dev/create-javascript-fetch-but-with-timeout</link><guid isPermaLink="true">https://raj-stark.hashnode.dev/create-javascript-fetch-but-with-timeout</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[fetch]]></category><category><![CDATA[SetTimeout]]></category><category><![CDATA[interview questions]]></category><dc:creator><![CDATA[Raj]]></dc:creator><pubDate>Wed, 04 Oct 2023 06:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697111527386/2ce60514-4337-491e-ad5a-57bacdfe1630.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Devs,</p>
<p>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.</p>
<p>So that is the problem statement, let's see how to conquer it.</p>
<h2 id="heading-goal">Goal:</h2>
<ul>
<li><p>We want a function that accepts a "URL" &amp; "Time" as a Parameter and like fetch(), and returns a Promise.</p>
</li>
<li><pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> fetchWithTimeOut = <span class="hljs-function">(<span class="hljs-params">url, time</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    });
  };
</code></pre>
</li>
<li><p>Then we call the normal fetch call, which we usually do most of the time .</p>
</li>
<li><pre><code class="lang-javascript">   <span class="hljs-keyword">const</span> fetchWithTimeOut = (url, time) = &gt;{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>((resolve, reject) = &gt;{
  <span class="hljs-comment">// Writing normal fetch method</span>
      fetch(url).then((resp) = &gt;{

        <span class="hljs-built_in">clearTimeout</span>(timeId);
        <span class="hljs-keyword">return</span> resp.json();

      }).then((data) = &gt;{

        resolve(data);

      }).
      catch((e) = &gt;{
        reject(e);
      });
    });
  };
</code></pre>
</li>
<li><p>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" <code>AbortController();</code></p>
<p>  The <code>AbortController</code> is used to provide a way to abort a network request created using the <code>fetch</code> .</p>
</li>
<li><p>Creation of the <code>AbortController</code> instance:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> AbortController();
</code></pre>
</li>
<li><p>Here, an <code>AbortController</code> instance is created. An <code>AbortController</code> is an object that allows you to associate an <code>AbortSignal</code> with it, which can be used to send an abort signal to one or more DOM requests, such as a <code>fetch</code> request.</p>
</li>
<li><pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> signal = controller.signal;
</code></pre>
<p>  The <code>signal</code> property of the <code>AbortController</code> object is used to get the associated <code>AbortSignal</code>. The <code>AbortSignal</code> is a signal object that can be used to abort one or more DOM requests, such as a <code>fetch</code> request.</p>
</li>
<li><pre><code class="lang-javascript">  fetch(url, { signal })
    .then(<span class="hljs-function">(<span class="hljs-params">resp</span>) =&gt;</span> {
      <span class="hljs-built_in">clearTimeout</span>(timeId);
      <span class="hljs-keyword">return</span> resp.json();
    })
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      resolve(data);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
      reject(e);
    });
</code></pre>
</li>
<li><p>When making a <code>fetch</code> request, you can pass the <code>AbortSignal</code> as an option in the request configuration. This associates the <code>AbortController</code> with the network request. If an abort signal is sent to the <code>AbortController</code> (e.g., by calling <code>controller.abort()</code>), it will cancel the network request, and any pending promises related to that request will be rejected.</p>
</li>
<li><p>A timer is set using, which will call <code>controller.abort()</code> after a specified <code>time</code> interval. If the network request doesn't complete within this timeout period, the <code>controller.abort()</code> function is called, which sends an abort signal to the associated <code>fetch</code> request. This effectively cancels the request.</p>
</li>
<li><pre><code class="lang-javascript">  timeId = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    controller.abort();
  }, time);
</code></pre>
</li>
</ul>
<hr />
<h3 id="heading-full-code">Full Code :</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchWithTimeOut = <span class="hljs-function">(<span class="hljs-params">url, time</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> timeId;
    <span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> AbortController();

    <span class="hljs-keyword">const</span> signal = controller.signal;

    fetch(url, { signal })
      .then(<span class="hljs-function">(<span class="hljs-params">resp</span>) =&gt;</span> {
        <span class="hljs-built_in">clearTimeout</span>(timeId);
        <span class="hljs-keyword">return</span> resp.json();
      })
      .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        resolve(data);
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        reject(e);
      });

    timeId = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      controller.abort();
    }, time);
  });
};

fetchWithTimeOut(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos/1"</span>, <span class="hljs-number">100</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">resp</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(resp);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(e);
  });
</code></pre>
]]></content:encoded></item></channel></rss>