소스 검색

Clock can now handle 'layers'. Every added layer reduces call speed of grouped components by <hz>/<# layers>.

master
Bryan Miller 5 년 전
부모
커밋
e7a447abfc
1개의 변경된 파일40개의 추가작업 그리고 20개의 파일을 삭제
  1. +40
    -20
      src/clock.js

+ 40
- 20
src/clock.js 파일 보기

@@ -1,41 +1,61 @@

class Clock{
constructor(){
constructor(layers){
layers = (typeof(layers === 'number') && layers > 0) ?
Math.floor(layers) :
1;
this.__ticktime = 1000;
this.__dt = 0;
this.__ltime = 0;
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 = 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')
this.__out.push(fn);
this.__out[layer].push(fn);
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;
}
}

Loading…
취소
저장