How to throttle my JS API fetch requests, using the rate-limit supplied by the host?

Solution 1:

Have you looked at debounce?

You can rate limit as in 1 call serviced in any defined period. Think about this as quantizing. The other way is to count calls over an extended time-frame and then either block further calls indefinitely or for a defined duration - it comes down to your preferred use-case.

Normally rate-limiting has more to do with security and the first option (1 call serviced in a defined period) is apt. If you are doing this for a web API, you may wish to reject requests that are 'too soon' and give the requestor some type of feedback with an appropriate HTTP status code.

How to implement all the different options is discussed here: https://thoughtspile.github.io/2018/07/07/rate-limit-promises/

EDIT: In response to OP comment below and reviewing the code... I think you're overthinking it.

FWIW I use debounce for the most part (equivalent to your "throttle") and it is literally used along the lines of debounce(functionReference,timeoutInMilliseconds).

The code looks like this

function debounce(func, waitFor) {
    let timeout;
    return (...args) => new Promise(resolve => {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(() => resolve(func(...args)), waitFor);
    });
}

Change your throttle(fetch) to my debounce(fetch,2500) and it should be enough. You don't need to have the assignment operation on that line, just call it, or write another function called debouncedFetch to encapsulate it and just call that from wherever you need to.