avocado-old/packages/timing/ticker.js
2019-03-19 18:05:42 -05:00

45 lines
866 B
JavaScript

import {compose} from '@avocado/core';
import {EventEmitter, Property} from '@avocado/mixins';
const decorate = compose(
EventEmitter,
Property('frequency', {
default: 0,
}),
);
class TickerBase {
constructor(frequency = 0) {
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);
}
}
}
}
}
export class Ticker extends decorate(TickerBase) {}