timer control

This commit is contained in:
cv
2021-04-08 13:41:51 +02:00
parent 4ba9ee452e
commit 2ae991a2c3
7 changed files with 226 additions and 105 deletions
+99 -30
View File
@@ -1,56 +1,125 @@
class Timer {
constructor(durationInSeconds) {
#current = null;
#finishAt = null;
#startedAt = null;
#pausedAt = null;
#pausedInterval = null;
#pausedTotal = null;
state = 'pause';
constructor() {}
// call setup separately
setupWithSeconds(seconds, autoStart = false) {
// aux
const now = new Date().getTime();
this.duration = durationInSeconds;
this.current = durationInSeconds;
this.finish = new Date().getTime() + durationInSeconds * 1000;
this.started = now;
// populate targets
this.#finishAt = now + seconds * 1000;
// start counting
this.#startedAt = now;
if (autoStart) {
this.state = 'start';
} else {
this.#pausedAt = now;
this.#pausedInterval = 0;
}
this.#pausedTotal = 0;
this.update();
}
// update()
update() {
// doesnt include start time yet
// get current time
const now = new Date().getTime();
this.current = (this.finish - now) * 0.001;
// check playstate
switch (this.state) {
case 'start':
// update current timer
this.#current = this.#finishAt + this.#pausedTotal - now;
break;
case 'pause':
// update paused time
this.#pausedInterval = now - this.#pausedAt;
break;
default:
console.error('Timer: no playstate on update call', this.state);
break;
}
}
// helpers
static toSeconds(millis) {
return Math.floor(Math.max(millis * 0.001), 0);
}
#getExpectedFinish() {
return (
this.#finishAt +
(this.#pausedInterval + this.#pausedTotal)
);
}
// getObject
getObject() {
this.update();
return {
duration: this.duration,
current: this.current,
finish: this.finish,
started: this.started,
currentSeconds: Timer.toSeconds(this.#current),
expectedFinish: this.#getExpectedFinish(),
startedAt: this.#startedAt,
};
}
// duration
getDuration(durationInSeconds) {
return this.duration;
}
setDuration() {
try {
this.duration = durationInSeconds;
return true;
} catch (e) {
console.error(e);
return false;
}
}
// current time in seconds
getCurrentInSeconds() {
// update timeStamp
this.update();
return this.current;
return Timer.toSeconds(this.#current);
}
// playback
start() {}
pause() {}
// playback
stop() {}
start() {
// do we need to change
if (this.state === 'start') return;
// update start time if needed
if (!this.#startedAt) {
this.#startedAt = new Date().getTime();
}
// check if there is paused time
if (this.#pausedInterval) {
this.#pausedTotal += this.#pausedInterval;
this.#pausedInterval = null;
}
// change state
this.state = 'start';
console.log('started');
}
pause() {
// do we need to change
if (this.state === 'pause') return;
// update pause time
this.#pausedAt = new Date().getTime();
// change state
this.state = 'pause';
console.log('paused');
}
stop() {
console.log('stop: not yet implemented');
return false;
}
roll() {
console.log('roll: not yet implemented');
return false;
}
}
module.exports = Timer;