humus-old/client/cycle-tracker.js

47 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-04-28 23:45:18 -05:00
import {compose, EventEmitter, Property} from '@avocado/core';
2019-04-23 15:27:55 -05:00
import {Ticker} from '@avocado/timing';
const decorate = compose(
EventEmitter,
Property('count', {
track: true,
}),
Property('jitter', {
track: true,
}),
);
export class CycleTracker extends decorate(class {}) {
constructor(targetFrequency) {
super();
this.count = 0;
this.jitter = [0, 0];
this.targetFrequency = targetFrequency;
this.ticker = new Ticker(.25);
this.trackCount = 0;
this.trackJitter = [0, 0];
this.ticker.on('tick', this.onTick, this);
}
onTick() {
this.count = this.trackCount * 4;
this.trackCount = 0;
this.jitter = this.trackJitter;
this.trackJitter = [0, 0];
this.emit('updated');
}
sample(elapsed) {
this.trackCount += 1;
const jitter = elapsed - this.targetFrequency;
if (jitter < 0 && elapsed < this.trackJitter[0]) {
this.trackJitter[0] = Math.round(1000 * jitter) / 1000;
}
if (jitter > 0 && elapsed > this.trackJitter[1]) {
this.trackJitter[1] = Math.round(1000 * jitter) / 1000;
}
this.ticker.tick(elapsed);
}
}