Throttling Lookups
Throttle the number of lookups the `doLookup` method can make
// throttle interval in milliseconds
const THROTTLE_INTERVAL = 5000;
// number of lookups allowed within the THROTTLE_INTERVAL
const THROTTLE_MAX_REQUESTS = 2;const THROTTLE_INTERVAL = 1000;
const THROTTLE_MAX_REQUESTS = 1;// Tracks the number of lookups we have made within the throttle window
let numLookupsInThrottleWindow = 0;
// Tracks the last time we started a new throttle window
let lastThrottleWindowStartTime = Date.now();/**
* Executes the `execFunc` if we have not reached our throttling limit,
* otherwise executes the `throttledCb` callback
*
* @param execFunc
* @param throttledCb
*/
function throttle(execFunc, throttledCb) {
// If we are past our throttle interval then we can reset the throttle window start time
// as well as the number of lookups we have made during the window.
if(Date.now() - lastThrottleWindowStartTime > THROTTLE_INTERVAL){
numLookupsInThrottleWindow = 0;
lastThrottleWindowStartTime = Date.now();
}
// As long as the number of lookups we have made during the window is less
// than the maximum allowed execute the `execFunc`.
if(numLookupsInThrottleWindow < THROTTLE_MAX_REQUESTS){
numLookupsInThrottleWindow++;
execFunc();
}else{
// Reached our throttle limit so just call the throttled callback
throttledCb(null);
}
}Last updated