Created
March 4, 2018 13:44
-
-
Save ndvbd/66f0bb0fc505a74aea044e06578bbfb2 to your computer and use it in GitHub Desktop.
ThrottledExecutor | Throttling functions invocations, and allowing only recent invocation to be made. | Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We want to define a throttledExecutor an object that constructs with a number, which is delay in seconds | |
// The object has one method: invokeThrottled, that accepts a function. | |
// The object remembers the last invocation time of the function (any function) - only one number to remember. | |
// If a function wasn't executed during the last 2 seconds, execute immediately. | |
// Otherwise, wait until 2 seconds will pass and execute the function | |
// If during the wait a new invocation arrived, forget about the old pending invocation (only remember the newest). | |
class ThrottledExecutor{ | |
constructor(delayInSeconds){ | |
this.delayInSeconds = delayInSeconds; | |
this.lastInvocation = false; | |
this.functionToExecute = false; | |
this.timeOutHandler = false; | |
} | |
setTimer(){ | |
var that = this; | |
clearTimeout(this.timeOutHandler); | |
this.timeOutHandler = setTimeout(function(){ // Set a timer ahead to check if new requests came in the meanwhile | |
if (that.functionToExecute != false){ | |
// We run invokeThrottled and not run the function directly, because we need to set another timeout. | |
that.invokeThrottled(that.functionToExecute); | |
} | |
}, that.delayInSeconds * 1000); | |
} | |
// The function functiontoInvoke will not necessarily be executed, if a newer invocation will come | |
invokeThrottled(functiontoInvoke){ | |
if (this.lastInvocation == false || (Date.now() - this.lastInvocation) > this.delayInSeconds*1000){ | |
this.functionToExecute = false;// If there is a function waiting, kill it. | |
this.lastInvocation = Date.now(); | |
functiontoInvoke(); // Execute immediately | |
this.setTimer(); | |
} else { | |
this.functionToExecute = functiontoInvoke; // The last request should be the one to activate after the right delay | |
this.setTimer(); // Not sure why I need it, but I saw that I need it. | |
} | |
} | |
} // EOF ThrottledExecutor | |
var throttledExecutor = new ThrottledExecutor(2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment