avocado-old/packages/timing/ticker.js
2019-05-02 03:38:45 -05:00

43 lines
819 B
JavaScript

import {compose, EventEmitter, Property} from '@avocado/core';
const decorate = compose(
EventEmitter,
Property('frequency', {
default: 0,
}),
);
export class Ticker extends decorate(class {}) {
constructor(frequency = 0) {
super();
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 = (this.remainder / this.frequency) << 0;
if (ticks > 0) {
this.remainder -= ticks * this.frequency;
for (let i = 0; i < ticks; ++i) {
this.emit('tick', this.frequency);
}
}
}
}
}