avocado-old/packages/timing/ticker.js

43 lines
824 B
JavaScript
Raw 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) {
const ticks = Math.floor(this.remainder / this.frequency);
if (ticks > 0) {
this.remainder -= ticks * this.frequency;
for (let i = 0; i < ticks; ++i) {
this.emit('tick', this.frequency);
}
}
}
}
}