SoFunction
Updated on 2025-04-14

Summary of the method of preventing duplicate requests by JavaScript interface

summary:

Preventing duplicate requests is a common problem in front-end development. Repeated requests will not only increase the server's load, but may also lead to problems such as data inconsistency!

1. Use anti-shake (Debounce) or Throttle

Debounce: Execute the function after the user stops triggering an event for a certain period of time. For example, when a user frequently clicks a button, only the last click will trigger the request.

function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => (context, args), wait);
    };
}

// How to useconst debouncedFetch = debounce((url) => fetch(url), 300);
debouncedFetch('/data');

Throttle: Specifies that function execution can only be triggered once within one unit of time. If the function is triggered multiple times within the same unit of time, only one effect will take effect.

function throttle(func, limit) {
    let lastFunc;
    let lastRan;
    return function() {
        const context = this;
        const args = arguments;
        if (!lastRan) {
            (context, args);
            lastRan = ();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function() {
                if (() - lastRan >= limit) {
                    (context, args);
                    lastRan = ();
                }
            }, limit - (() - lastRan));
        }
    };
}

​​​​​​​// How to useconst throttledFetch = throttle((url) => fetch(url), 2000);
throttledFetch('/data');

2. Use flags (Flag) to prevent repeated requests

By setting a flag bit, subsequent requests are blocked while requests are in progress.

let isFetching = false;

function fetchData(url) {
    if (isFetching) return;
    isFetching = true;

​​​​​​​    fetch(url)
        .then(response => ())
        .then(data => {
            // Process the returned data        })
        .catch(error => {
            ('Error:', error);
        })
        .finally(() => {
            isFetching = false;
        });
}

3. Use AbortController

AbortController allows you to abort requests when needed.

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

function fetchData(url) {
    fetch(url, { signal })
        .then(response => ())
        .then(data => {
            // Process the returned data        })
        .catch(error => {
            if ( === 'AbortError') {
                ('Fetch aborted');
            } else {
                ('Error:', error);
            }
        });
}

​​​​​​​// Call where requests need to be aborted ()();

4. Use third-party libraries (such as Axios and Redux-Saga)

If you are using Axios or Redux-Saga, you can use the middleware features provided by these libraries to prevent duplicate requests.

Axios Cancel Token

Axios supports the function of canceling requests, which can be implemented through CancelToken.

const axios = require('axios');
const CancelToken = ;
let cancel;

​​​​​​​function fetchData(url) {
    if (cancel) {
        cancel('Operation canceled due to new request.');
    }
    cancel = null;
    const source = ();
    (url, { cancelToken:  })
        .then(response => {
            // Process the returned data        })
        .catch(thrown => {
            if ((thrown)) {
                ('Request canceled', );
            } else {
                ('Error:', thrown);
            }
        });
}

Summarize

The above are several common methods to prevent duplicate requests, and you can choose the appropriate method according to the specific scenario. Anti-shake and throttling are suitable for frequently triggered events, flags and AbortController are suitable for situations where manual control of requests is required, while third-party libraries provide greater functionality and flexibility.

This is the end of this article about the method of preventing duplicate requests by JavaScript interface. For more related content related to JavaScript interface, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!