Skip to content

Instantly share code, notes, and snippets.

@Almenon
Created March 11, 2018 04:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Almenon/f2043143e6e7b4610817cb48c962d4d5 to your computer and use it in GitHub Desktop.
Save Almenon/f2043143e6e7b4610817cb48c962d4d5 to your computer and use it in GitHub Desktop.
typescript throttling / ratelimiting
/**
* class for limiting the rate of function calls.
* Thanks to Pat Migliaccio.
* see https://medium.com/@pat_migliaccio/rate-limiting-throttling-consecutive-function-calls-with-queues-4c9de7106acc
* @example let l = new limit(); let logMessageLimited = l.throttleAndQueue(msg => { console.log(msg); }, 500);
*/
class limit{
public callQueue = []
/**
* limits your function to be called at most every W milliseconds, where W is wait.
* Calls to your func that happen more often than W get queued up to be called later.
* @param fn
* @param wait
*/
throttleAndQueue(fn:Function, wait:number){
let isCalled = false;
let self = this;
let caller = function(){
if (self.callQueue.length && !isCalled){
isCalled = true;
self.callQueue.shift().call();
setTimeout(function(){
isCalled = false;
caller();
}, wait);
}
};
return function(...args){
self.callQueue.push(fn.bind(this, ...args));
caller();
};
}
}
/**
* limits your function to be called at most every W milliseconds, where W is wait.
* Calls over W get dropped.
* Thanks to Pat Migliaccio.
* see https://medium.com/@pat_migliaccio/rate-limiting-throttling-consecutive-function-calls-with-queues-4c9de7106acc
* @param fn
* @param wait
* @example let throttledFunc = throttle(myFunc,500);
*/
function throttle(fn:Function, wait:number){
let isCalled = false;
return function(...args){
if (!isCalled){
fn(...args);
isCalled = true;
setTimeout(function(){
isCalled = false;
}, wait)
}
};
}
let myLimit = new limit()
let logMessageLimited = myLimit.throttleAndQueue(msg => { console.log(msg); }, 500);
setTimeout(() => {
myLimit.callQueue = []
}, 1000);
for (let i = 0; i < 3; i++){
logMessageLimited(`[Message Log] Action (${i}) rate limited.`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment