Abort Fetch | Javascript

 

//HTML
<button id="download">Download</button>
<button id="abort">Abort</button>

//JS
let controller;

document.querySelector('#download').addEventListener('click', () => {
  controller = new AbortController();
  const signal = controller.signal;
  fetch('https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4', {signal})
    .then(() => console.log('done'));
});

document.querySelector('#abort').addEventListener('click', function() {
  controller.abort();
});
 

AI Explanation

This code snippet contains HTML with two buttons, "Download" and "Abort", and JavaScript code that handles the download process and allows the user to abort it. Explanation of the code: 1. Two buttons are defined in the HTML file with IDs "download" and "abort". 2. In the JavaScript code: a. A variable named `controller` is declared to store an AbortController object. b. An event listener is added to the "Download" button. When this button is clicked, a new AbortController instance is created and assigned to the `controller` variable. The controller's signal is then passed as an option to the fetch function, which initiates a request to download a video file from a specific URL. If the download is successful, the message "done" is logged to the console. c. Another event listener is added to the "Abort" button. When this button is clicked, the `abort()` method is called on the `controller` object, which cancels the fetch request and stops the download process. In summary, this code allows the user to start downloading a video file by clicking the "Download" button and provides the functionality to abort the download by clicking the "Abort" button using the AbortController API in JavaScript.