Class: Throttle

Throttle(limit, window)

The Throttle rate-limits access to a resource over a moving time window using a 'leaky bucket' algorithm.

Constructor

new Throttle(limit, window)

Creates a throttle.

Parameters:
Name Type Description
limit number

Number of requests allowed.

window number

Per this time window (in ms).

Source:

Members

nextSlot

Returns the time (ms) until the throttle opens again (plus 1ms). Note that this getter just returns the delay - it does not update the throttle.

Source:

remainder

Returns how much capacity is left for this time window. This value is useful for selecting the least constricted resource among a pool of throttled resources.

Source:

waitTime

Returns the time (ms) until a next request can be honored (plus 1ms if there's a wait). This is useful in case multiple throttles need to be checked before a request can be consumed. Note that this getter updates the throttle's state before it produces a value.

Source:

Methods

consume()

Consumes one unit of capacity. Should only be called if waitTime > 0.

Source:
Example
function doSomething() {
    const delay = myThrottle.waitTime;
    if (delay > 0)
        return "I can't do this right now, but in " + delay + "ms I can.";

    myThrottle.consume();
    // Do it.
    return "I did it";
}

permit()

Returns a promise that is guaranteed to resolve (in FIFO order), but not sooner than the throttle allows. For certain use cases this provides a more convenient alternative compared to using the waitTime and consume() pair.

Source:
Example
async function doSomething() {
    await myThrottle.permit();   // Resolves immediately or as soon as possible.
    // Do it.
    return "I did it";
}

reset()

Resets the throttle to maximum capacity.

Source: