There are several ways to stop old API calls when calling a new API in JavaScript.

  1. Cancel previous requests using AbortController: You can create an instance of AbortController and use it to cancel the previous requests before making a new request.

Example:

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

// cancel the previous request
controller.abort();

// make a new request
fetch(url, { signal })
  .then(response => {
    // handle response
  })
  .catch(error => {
    // handle error
  });
  1. Debouncing: Debouncing is a technique that delays the execution of a function until a certain amount of time has passed without any other calls being made. You can use debounce to avoid making unnecessary API calls.

Example:

function debounce(func, delay) {
  let timeoutId;
  return function (...args) {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

const debouncedApiCall = debounce(() => {
  fetch(url)
    .then(response => {
      // handle response
    })
    .catch(error => {
      // handle error
    });
}, 500);

// call the debounced function
debouncedApiCall();
  1. Throttling: Throttling is a technique that limits the rate at which a function can be called. You can use throttling to prevent making too many API calls in a short period of time.

Example:

function throttle(func, limit) {
  let inThrottle;
  return function (...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => {
        inThrottle = false;
      }, limit);
    }
  };
}

const throttledApiCall = throttle(() => {
  fetch(url)
    .then(response => {
      // handle response
    })
    .catch(error => {
      // handle error
    });
}, 500);

// call the throttled function
throttledApiCall();
js stop old post api calling when calling new api

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

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