I was reading some game's source code on Github and saw this game loop implementation for the first time:
var lastTime = 0;
var maxTime = 1/30;
/**
* @param {DOMHighResTimeStamp} curTime requestAnimationFrame provides this value automatically
*/
this.loop = function(curTime) {
requestAnimationFrame(Game.loop);
// Same as division by 1000
var dt = (curTime - lastTime) * 0.001;
if(dt > maxTime) {
dt = maxTime;
}
for(var i = 0, len = boards.length; i < len; i++) {
if(boards[i]) {
boards[i].step(dt);
boards[i].draw(Game.ctx);
}
}
lastTime = curTime;
};
The key thing: The game updates and draws at every step, but the delta time is capped at the desired maximum delta. That way, if a frame takes too long, the next frame steps with a constant delta.
What are the pros and cons of this approach? I imagine it's useful for preventing huge entity movements caused by a long timestep, but can it cause problems?
Edit
Use curTime
as provided by window.requestAnimationFrame
in order to simplify stuff and avoid comments that don't deal with my main question.