Created
October 18, 2016 16:56
-
-
Save jvlppm/b4fd92e4579d59d0a9ea5656b865e0d2 to your computer and use it in GitHub Desktop.
This file contains 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
export class HighResolutionTimer { | |
private totalTicks = 0; | |
private timer: number | undefined; | |
private startTime: number | undefined; | |
private currentTime: number | undefined; | |
private deltaTime = 0; | |
constructor(public duration: number, public callback: (timer: HighResolutionTimer) => void) { | |
} | |
run() { | |
let lastTime = this.currentTime; | |
this.currentTime = Date.now(); | |
if (!this.startTime) { | |
this.startTime = this.currentTime; | |
} | |
if (lastTime !== undefined) { | |
this.deltaTime = (this.currentTime - lastTime); | |
} | |
this.callback(this); | |
let nextTick = this.duration - (this.currentTime - (this.startTime + (this.totalTicks * this.duration))); | |
this.totalTicks++; | |
this.timer = setTimeout(() => { | |
this.run(); | |
}, nextTick); | |
} | |
stop() { | |
if (this.timer !== undefined) { | |
clearTimeout(this.timer); | |
this.timer = undefined; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment