Problem statement:
We have a number of functions in our web application that are getting called too frequently. We'd like you to create a function that, given a function and a time interval, returns a new function that we can call as often as we like, but ensures that the original function is never called more than once per interval.
Example usage:
limitedDoSomething = rateLimit(doSomething, 500);
Now calls to
limitedDoSomething
will simply calldoSomething
, but never more than once every 500 milliseconds.
Test Cases:
function logHello(){ // just a sample function
console.log('Hello!');
}
limitedDoSomething = rateLimit(logHello, 500);
limitedDoSomething(); // should log “Hello!”
window.setTimeout(function(){
limitedDoSomething(); // should not log “Hello!"
}, 400);
window.setTimeout(function(){
limitedDoSomething(); // should log “Hello!"
}, 500);
My solution:
function rateLimit(func, limit){
var lastInvokedTimestamp;
return function(){
if(typeof lastInvokedTimestamp === 'undefined' || Date.now() - lastInvokedTimestamp >= limit){
lastInvokedTimestamp = Date.now();
console.log('go ahead!');
return func();
} else {
console.log('too early!');
return;
}
};
}
// run test cases
function logHello(){ // just a sample function
console.log('Hello!');
}
limitedDoSomething = rateLimit(logHello, 500);
limitedDoSomething(); // should log “Hello!”
window.setTimeout(function(){
limitedDoSomething(); // should not log “Hello!"
}, 400);
window.setTimeout(function(){
limitedDoSomething(); // should log “Hello!"
}, 500);
I would love to know if there is a way to improve my solution.