Created
August 30, 2017 15:59
-
-
Save lunaroyster/3e4b6d60830a19645617ef14676267c6 to your computer and use it in GitHub Desktop.
Generates ticks. Adjust tick length. Start and stop generator.
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
var on = function(name, handler) { | |
if(this._events.hasOwnProperty(name)) { | |
this._events[name].push(handler); | |
} | |
else { | |
this._events[name] = [handler]; | |
} | |
}; | |
var invoke = function(name, args) { | |
var res = []; | |
if(!this._events.hasOwnProperty(name)) return; | |
if (!args || !args.length) args = []; | |
for (var fn of this._events[name]) { | |
if(fn==undefined) continue; | |
res.push(fn.apply(this, args)); | |
} | |
return res; | |
}; | |
class TickGenerator { | |
constructor(tickLength) { | |
this._events = {}; | |
this.on = on.bind(this); | |
this.invoke = invoke.bind(this); | |
this.tickLength = tickLength || 1000; | |
this.on("tick", function() {this.callback()}); | |
} | |
start() { | |
if(this._ticking) return; | |
this._tickerID = setInterval(()=> {this.invoke("tick")}, this.tickLength); | |
this._ticking = true; | |
} | |
stop() { | |
if(!this._ticking) return; | |
clearInterval(this._tickerID); | |
this._ticking = false; | |
} | |
set callback(value) { | |
if(typeof(value)!="function") throw Error("Invalid function"); | |
this._callback = value; | |
} | |
get callback() { | |
return this._callback || (()=>{}); | |
} | |
set tickLength(value) { | |
if(typeof(value)!="number") throw Error("Invalid tick length"); | |
this._tickLength = value; | |
if(!this._ticking) return; | |
this.stop(); | |
this.start(); | |
} | |
get tickLength() { | |
return this._tickLength; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment