Home > Web Front-end > JS Tutorial > How Can I Cancel Fetch Requests in JavaScript?

How Can I Cancel Fetch Requests in JavaScript?

Barbara Streisand
Release: 2024-11-18 01:29:02
Original
199 people have browsed it

How Can I Cancel Fetch Requests in JavaScript?

Canceling Fetch Requests: Exploring Built-in Mechanisms

JavaScript's new fetch() API provides a convenient way to make HTTP requests. However, a long-standing question remains: is there a built-in mechanism for canceling these requests mid-flight?

The Signal Parameter

As of September 2017, fetch() supports the signal parameter. This parameter accepts an AbortSignal object, which enables the controlled abortion of a fetch request.

Implementation

To cancel a fetch request, follow these steps:

  1. Create an AbortController instance.
  2. Obtain the AbortSignal object from the AbortController.
  3. Pass the AbortSignal to fetch() in the signal parameter.
  4. When desired, call controller.abort() to terminate the request.

Example

Consider the following code snippet:

// Initialize an AbortController and its AbortSignal
const controller = new AbortController();
const signal = controller.signal;

// Perform a fetch request with the AbortSignal
fetch(urlToFetch, {
  signal,
});

// Abort the request at any time
controller.abort();
Copy after login

Browser Support

Initially, support for AbortSignal was limited. However, as of March 2020, most major browsers (Edge, Firefox, Chrome, Safari, Opera, etc.) have implemented this feature, making it a widely accessible solution.

While not all browsers may currently support AbortSignal, its widespread availability indicates that canceling fetch requests in-flight is now a commonplace capability in JavaScript development.

The above is the detailed content of How Can I Cancel Fetch Requests in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template