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

How Can I Interrupt HTTP Fetch Requests in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-23 05:19:081094browse

How Can I Interrupt HTTP Fetch Requests in JavaScript?

Interrupting HTTP Fetch Requests with Cancellation

The introduction of fetch() in JavaScript has revolutionized HTTP request handling, providing a versatile and intuitive interface. However, concerns often arise regarding the ability to terminate these requests prematurely.

Abort Mechanisms in fetch()

As of September 2017, fetch() incorporated a significant enhancement: support for the signal parameter. This parameter allows developers to cancel requests using an AbortController and its corresponding AbortSignal. Initially, browser support was limited, but now (as of March 2020), most major browsers (Edge, Firefox, Chrome, Safari, Opera, and others) fully embrace this functionality.

Implementation

The cancelation process involves four steps:

  1. Create an AbortController:
const controller = new AbortController()
  1. Obtain the AbortSignal:
const signal = controller.signal
  1. Pass the signal to fetch():
fetch(urlToFetch, {
    method: 'get',
    signal: signal,
})
  1. Abort the request whenever desired:
controller.abort();

Example

To illustrate how it works in practice, consider the following example:

// Create an instance.
const controller = new AbortController()
const signal = controller.signal

/*
// Register a listenr.
signal.addEventListener("abort", () => {
    console.log("aborted!")
})
*/


function beginFetching() {
    console.log('Now fetching');
    var urlToFetch = "https://httpbin.org/delay/3";

    fetch(urlToFetch, {
            method: 'get',
            signal: signal,
        })
        .then(function(response) {
            console.log(`Fetch complete. (Not aborted)`);
        }).catch(function(err) {
            console.error(` Err: ${err}`);
        });
}


function abortFetching() {
    console.log('Now aborting');
    // Abort.
    controller.abort()
}

By invoking controller.abort(), the request can be interrupted at any time.

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

Statement:
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