AbortController: abort() method
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2019.
Note: This feature is available inWeb Workers.
Theabort()
method of theAbortController
interface aborts an asynchronous operation before it has completed.This is able to abortfetch requests, the consumption of any response bodies, or streams.
Syntax
abort()abort(reason)
Parameters
reason
OptionalThe reason why the operation was aborted, which can be any JavaScript value.If not specified, the reason is set to "AbortError"
DOMException
.
Return value
None (undefined
).
Examples
In the following snippet, we aim to download a video using theFetch API.
We first create a controller using theAbortController()
constructor, then grab a reference to its associatedAbortSignal
object using theAbortController.signal
property.
When thefetch request is initiated, we pass in theAbortSignal
as an option inside the request's options object (the{signal}
below). This associates the signal and controller with the fetch request and allows us to abort it by callingAbortController.abort()
, as seen below in the second event listener.
const controller = new AbortController();const signal = controller.signal;const url = "video.mp4";const downloadBtn = document.querySelector(".download");const abortBtn = document.querySelector(".abort");downloadBtn.addEventListener("click", fetchVideo);abortBtn.addEventListener("click", () => { controller.abort(); console.log("Download aborted");});function fetchVideo() { fetch(url, { signal }) .then((response) => { console.log("Download complete", response); }) .catch((err) => { console.error(`Download error: ${err.message}`); });}
Note:Whenabort()
is called, thefetch()
promise rejects with anError
of typeDOMException
, with nameAbortError
.
You can find afull working example on GitHub; you can also see itrunning live.
Specifications
Specification |
---|
DOM # ref-for-dom-abortcontroller-abortcontroller① |