avocado-old/packages/timing/ticker.js

43 lines
819 B
JavaScript
Raw Permalink Normal View History

2019-04-28 23:45:03 -05:00
import {compose, EventEmitter, Property} from '@avocado/core';
2019-03-19 18:05:42 -05:00
const decorate = compose(
EventEmitter,
Property('frequency', {
default: 0,
}),
);
export class Ticker extends decorate(class {}) {
2019-03-19 18:05:42 -05:00
constructor(frequency = 0) {
super();
2019-03-19 18:05:42 -05:00
this.remainder = 0;
this.frequency = frequency;
}
remaining() {
return 1 - this.remainder / this.frequency;
}
reset() {
this.remainder = 0;
}
tick(elapsed) {
if (0 === this.frequency) {
return;
}
this.remainder += elapsed;
if (this.remainder >= this.frequency) {
2019-05-02 03:38:45 -05:00
const ticks = (this.remainder / this.frequency) << 0;
2019-03-19 18:05:42 -05:00
if (ticks > 0) {
this.remainder -= ticks * this.frequency;
for (let i = 0; i < ticks; ++i) {
this.emit('tick', this.frequency);
}
}
}
}
}