class Clock{ constructor(layers){ layers = (typeof(layers === 'number') && layers > 0) ? Math.floor(layers) : 1; this.__ticktime = 1000; this.__dt = -1; this.__out = []; this.__cl = 0; for (let i=0; i < layers; i++) this.__out.push([]); } get hz(){return Math.floor(1000 / this.__ticktime);} set hz(hz){ if(hz >= 1){ this.__ticktime = 1000 / hz; this.__dt = -1; } } 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') this.__out[layer].push(fn); return this; } // NOTE: dt in milliseconds. tick(dt){ let extraTick = false; if (this.__dt < 0){ this.__dt = 0; extraTick = true; } 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; } } module.exports = Clock;