WebAPIs: AbortController reference
23 July 2023 (Updated 23 July 2023)
On this page
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")
}
})
Sources
Tagged:
Web APIs
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment