Created
July 9, 2019 20:07
-
-
Save rdjpalmer/7de545dd057d8e35d874d60e3c6dd742 to your computer and use it in GitHub Desktop.
Timo's timer class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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