sajad torkamani

In a nutshell

The AbortController API gives you a controller object that you can use to abort web requests programmatically.

How to use

// 1. Create controller
const controller = new AbortController()

// 2. Pass controller signal to the fetch API or to another data-fetching // library like Axios
function fetchVideo() {
  controller = new AbortController()
  const signal = controller.signal
  fetch('video.mp4', { signal }) // Note that we pass our controller signal here
    .then((response) => {
      console.log("Download complete", response)
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`)
    })
}

const downloadBtn = document.querySelector(".download")
const abortBtn = document.querySelector(".abort")

downloadBtn.addEventListener('click'), fetchVideo)

// 3. Programmatically abort requests using the controller.abort method
abortBtn.addEventListener('click', () => {
  if (controller) {
    controller.abort()
    console.log("Download aborted")
  }
})

Live demo

Sources

Tagged: Web APIs

Leave a comment

Your email address will not be published. Required fields are marked *