Created
November 14, 2018 03:13
-
-
Save FMCorz/64317bbeeee9d0dd84e064c3aba24500 to your computer and use it in GitHub Desktop.
Basic module to simply throttle a function call
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
define([], function() { | |
/** | |
* Throttler. | |
* | |
* @param {Number} delay The delay. | |
*/ | |
function Throttler(delay) { | |
this.delay = delay || 300; | |
this.timeout = null; | |
this.time = new Date(); | |
} | |
Throttler.prototype.cancel = function() { | |
clearTimeout(this.timeout); | |
}; | |
Throttler.prototype.schedule = function(callback) { | |
var now = new Date(); | |
if (this.time.getTime() + this.delay > now) { | |
clearTimeout(this.timeout); | |
} | |
this.time = now; | |
this.timeout = setTimeout(callback, this.delay); | |
}; | |
return Throttler; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment