Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

AbortController: abort() method

BaselineWidely available

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

js
abort()abort(reason)

Parameters

reasonOptional

The 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.

js
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①

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp