Skip to content

Instantly share code, notes, and snippets.

@zandzpider
Created April 14, 2018 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zandzpider/0b2516df263e528febeef5eb0d204699 to your computer and use it in GitHub Desktop.
Save zandzpider/0b2516df263e528febeef5eb0d204699 to your computer and use it in GitHub Desktop.
const level = new Level(); // game logic
const timer = new Timer(1/60);
timer.update = function update(deltaTime) {
level.update(deltaTime);
};
timer.start();
export default class Timer {
constructor(deltaTime = 1/60) {
let accumulatedTime = 0;
let lastTime = 0;
this.updateProxy = (time) => {
accumulatedTime += (time - lastTime)/1000;
if (accumulatedTime > 1) {
accumulatedTime = 1;
}
while(accumulatedTime > deltaTime) {
this.update(deltaTime);
accumulatedTime -= deltaTime;
}
lastTime = time;
this.enqueue();
}
}
enqueue() {
requestAnimationFrame(this.updateProxy);
}
start() {
this.enqueue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment