Created
September 29, 2014 11:27
-
-
Save grifdail/836196d584d9f9d6b396 to your computer and use it in GitHub Desktop.
Framerate fix
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
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