To achieve this functionality, you can use the AbortController interface in JavaScript.

Here's an example of how to use it:

let controller = new AbortController();
let signal = controller.signal;

// function to make API call
async function fetchData() {
  try {
    const response = await fetch('https://example.com/data', { signal });
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

// button click event to stop running API
document.querySelector('button').addEventListener('click', () => {
  controller.abort();
});

// button click event to run API again
document.querySelector('button').addEventListener('click', () => {
  controller = new AbortController();
  signal = controller.signal;
  fetchData();
});

In this example, we create a new AbortController and signal variable to pass to the fetch API call. When the "stop" button is clicked, we call controller.abort() to cancel the API request.

When the "run again" button is clicked, we create a new AbortController and signal variable, and call the fetchData() function again. This will start a new API request with the new signal.

stop the running api when pressing a button and run the same api again in js

原文地址: https://www.cveoy.top/t/topic/bcO3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录