Skip to content

Instantly share code, notes, and snippets.

@grifdail
Created September 29, 2014 11:27
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 grifdail/836196d584d9f9d6b396 to your computer and use it in GitHub Desktop.
Save grifdail/836196d584d9f9d6b396 to your computer and use it in GitHub Desktop.
Framerate fix
function loop(framerate,update,draw) {
//Update and draw are callbacK function
var requestedInterval = 1000/framerate;
var timeSinceLastUpdate = 0;
var lastFrameTimeStamp = 0;
function loopFunction() {
requestAnimationFrame(loopFunction);
var now = Date.now();
var dt = now - lastFrameTimeStamp; //Classic DeltaTime
timeSinceLastUpdate += dt;
lastFrameTimeStamp = now;
if (timeSinceLastUpdate>3*requestedInterval) { //In case the browser cannot catch up with the update. It may create a vicouse circle
timeSinceLastUpdate = 3*requestedInterval
}
while (timeSinceLastUpdate>requestedInterval) {
timeSinceLastUpdate-=requestedInterval;
if (update) {
update();
}
}
if (draw) {
draw(dt);
}
}
loopFunction();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment