2019-03-19 18:05:42 -05:00
|
|
|
import {compose} from '@avocado/core';
|
|
|
|
import {EventEmitter, Property} from '@avocado/mixins';
|
|
|
|
|
|
|
|
const decorate = compose(
|
|
|
|
EventEmitter,
|
|
|
|
Property('frequency', {
|
|
|
|
default: 0,
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
2019-03-27 16:18:27 -05:00
|
|
|
export class Ticker extends decorate(class {}) {
|
2019-03-19 18:05:42 -05:00
|
|
|
|
|
|
|
constructor(frequency = 0) {
|
2019-03-27 16:18:27 -05:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|