Skip to content

Instantly share code, notes, and snippets.

@rdjpalmer
Created July 9, 2019 20:07
Show Gist options
  • Save rdjpalmer/7de545dd057d8e35d874d60e3c6dd742 to your computer and use it in GitHub Desktop.
Save rdjpalmer/7de545dd057d8e35d874d60e3c6dd742 to your computer and use it in GitHub Desktop.
Timo's timer class
class Timer {
constructor(startTime = 0, onUpdate = () => {}) {
this.startTime = startTime;
this.onUpdate = onUpdate;
}
offset = null;
interval = null;
recording = false;
start = () => {
this.recording = true;
this.offset = Date.now();
this.interval = setInterval(this.update, 1000);
};
update = () => {
const newTime = this.startTime + this.calculateTimeOffset();
this.startTime = newTime;
this.onUpdate(newTime);
};
stop = () => {
clearInterval(this.interval);
this.interval = null;
this.recording = false;
};
calculateTimeOffset = () => {
const now = Date.now();
const newOffset = now - this.offset;
this.offset = now;
return newOffset;
};
}
export default Timer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment