So I've read the famous article at http://www.koonsolo.com/news/dewitters-gameloop/comment-page-2/#comments which describes different methods of implementing a game loop. I've tried to implement the final method that is described in the article in Javascript (ignoring interpolation for the time being):
var Timer = {
pastTime : 0,
currentTime : 0,
started : false,
//starts the timer
start: function(){
if(!this.started){
this.started = true;
this.pastTime = new Date().getTime();
}
},
//gets the time in MILLSECONDS
getTime: function(){
return new Date().getTime() - this.pastTime;
},
//stops the timer but does not reset it (i.e. getTime() can still be
called to get the time between start() and end())
end: function(){
if(this.started){
this.currentTime = new Date().getTime();
this.started = false;
return this.currentTime - this.pastTime;
}
},
//resets the timer
reset: function(){
this.pastTime = 0;
this.currentTime = 0;
this.started = false;
}
var maxFrameSkip = 5;
var nextTick = new Date().getTime();
var TICKS_PER_SECOND = 25;
var tickTimeMillis = 1000 / TICKS_PER_SECOND;
var ticksPerSecondReal = 0;
var ticksCounter = 0;
var timer = Object.create(Timer);
var loops = 0;
function gameLoop(){
loops = 0;
timer.start();
while(new Date().getTime() > nextTick && loops < maxFrameSkip){
update();
ticksCounter++;
nextTick += tickTimeMillis;
loops++;
}
draw();
if(timer.getTime() >= 1000){
ticksPerSecondReal = ticksCounter;
ticksCounter = 0;
timer.reset();
}
console.log(ticksPerSecondReal);
window.requestAnimationFrame(gameLoop);
}
gameLoop();
So the problem that I'm having is that the console.log(ticksPerSecondReal) should always be giving me 25 because that's the constant ticks per second that I want and have set up. What I end up getting is an alternating number that is 25 and 26. So periodically (~1 second) it will be 25 and then 26 and then 25 and so on. And sometimes (much less frequently) it will even give a result of 27. It keeps switching back and forth when it should be constant at 25. What is the issue here?