Created
March 27, 2022 08:52
-
-
Save gsimone/1a7816831421c18b274bd46a3a60a1a3 to your computer and use it in GitHub Desktop.
Time provider defined at construction
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 Clock { | |
constructor( autoStart = true ) { | |
this.autoStart = autoStart; | |
this.startTime = 0; | |
this.oldTime = 0; | |
this.elapsedTime = 0; | |
this.running = false; | |
this.timeProvider = ( typeof performance === 'undefined' ? Date : performance ); | |
} | |
now = () => { | |
return this.timeProvider.now(); | |
} | |
start() { | |
this.startTime = this.now(); | |
this.oldTime = this.startTime; | |
this.elapsedTime = 0; | |
this.running = true; | |
} | |
stop() { | |
this.getElapsedTime(); | |
this.running = false; | |
this.autoStart = false; | |
} | |
getElapsedTime() { | |
this.getDelta(); | |
return this.elapsedTime; | |
} | |
getDelta() { | |
let diff = 0; | |
if ( this.autoStart && ! this.running ) { | |
this.start(); | |
return 0; | |
} | |
if ( this.running ) { | |
const newTime = this.now(); | |
diff = ( newTime - this.oldTime ) / 1000; | |
this.oldTime = newTime; | |
this.elapsedTime += diff; | |
} | |
return diff; | |
} | |
} | |
export { Clock }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment