JSFiddle - React, Tailwind, and code Playground

by ibcaliax

HTML

<h1>Example of fetch abort</h1>
<hr>
<button onclick="beginFetching();">
    Begin
</button>
<button onclick="abortFetching();">
    Abort
</button>

JavaScript

// Create an AbortController instance and a signal to abort fetchs request later.  
const abortController = new AbortController();
const abortSignal = abortController.signal;

// On page leave abort all ongoing fetchs.
window.addEventListener('beforeunload', () => {
  console.log("window 'beforeunload' event, aborting fetchs()");

  abortFetching();
});

async function beginFetching() {
  console.log('now fetching...');

  const urlToFetch = "https://httpbin.org/delay/10";

  try {
    // Pass the same abortSignal to all fetch() calls.
    await fetch(urlToFetch, {
      method: 'get',
      signal: abortSignal,
    });

    console.log('fetch completed (not aborted)');
  } catch (error) {
    console.error(`fetch() failed [error.name:${error.name}]: ${error.message}`);
  }
}

function abortFetching() {
  console.log('Now aborting');

  // Abort fetchs.
  abortController.abort()
}