| class Clock{ | class Clock{ | ||||
| constructor(){ | |||||
| constructor(layers){ | |||||
| layers = (typeof(layers === 'number') && layers > 0) ? | |||||
| Math.floor(layers) : | |||||
| 1; | |||||
| this.__ticktime = 1000; | this.__ticktime = 1000; | ||||
| this.__dt = 0; | |||||
| this.__ltime = 0; | |||||
| this.__dt = -1; | |||||
| this.__out = []; | this.__out = []; | ||||
| this.__cl = 0; | |||||
| for (let i=0; i < layers; i++) | |||||
| this.__out.push([]); | |||||
| } | } | ||||
| get hz(){return Math.floor(1000 / this.__ticktime);} | get hz(){return Math.floor(1000 / this.__ticktime);} | ||||
| set hz(hz){ | set hz(hz){ | ||||
| if(hz >= 1){ | if(hz >= 1){ | ||||
| this.__ticktime = 1000 / hz; | this.__ticktime = 1000 / hz; | ||||
| this.__dt = 0; | |||||
| this.__ltime = 0; | |||||
| this.__dt = -1; | |||||
| } | } | ||||
| } | } | ||||
| clk(fn){ | |||||
| get layers(){return this.__out.length;} | |||||
| clk(fn, layer){ | |||||
| layer = (typeof(layer === 'number') && layer >= 0) ? | |||||
| Math.floor(layer) : | |||||
| 0; | |||||
| if (layer < 0 || layer >= this.__out.length) | |||||
| throw new RangeError("Layer out of bounds."); | |||||
| if (typeof(fn) === 'function') | if (typeof(fn) === 'function') | ||||
| this.__out.push(fn); | |||||
| this.__out[layer].push(fn); | |||||
| return this; | return this; | ||||
| } | } | ||||
| tick(){ | |||||
| let ctime = (new Date()).getTime(); | |||||
| if(this.__ltime !== 0){ | |||||
| this.__dt += ctime - this.__ltime; | |||||
| while(this.__dt > this.__ticktime){ | |||||
| this.__out.forEach((fn)=>{fn();}); | |||||
| this.__dt -= this.__ticktime | |||||
| } | |||||
| } else { | |||||
| // Call all of the callbacks immediately. This is the first | |||||
| // legit tick! | |||||
| this.__out.forEach((fn)=>{fn();}); | |||||
| // NOTE: dt in milliseconds. | |||||
| tick(dt){ | |||||
| let extraTick = false; | |||||
| if (this.__dt < 0){ | |||||
| this.__dt = 0; | |||||
| extraTick = true; | |||||
| } | } | ||||
| this.__ltime = ctime; | |||||
| let proc = (ddt) => { | |||||
| this.__out[this.__cl].forEach((fn)=>{fn();}); | |||||
| if (ddt) | |||||
| this.__dt -= this.__ticktime; | |||||
| if (this.__out.length > 1) | |||||
| this.__cl = (this.__cl === this.__out.length - 1) ? 0 : this.__cl + 1; | |||||
| }; | |||||
| this.__dt += dt; | |||||
| while(this.__dt > this.__ticktime) | |||||
| proc(true); | |||||
| if (extraTick) | |||||
| proc(false); | |||||
| return this; | return this; | ||||
| } | } | ||||
| } | } |