views:

412

answers:

3

Is there a simple way to make a game loop in JavaScript? something like...

onTimerTick() {
  // update game state
}
+8  A: 
setInterval(onTimerTick, 33); // 33 milliseconds = ~ 30 frames per sec

function onTimerTick() {
    // Do stuff.
}
J-P
You'd probably want to reverse the order of the first line and the rest. ;)
Amber
Go on, make it 33ms... ;-)
T.J. Crowder
Done ;) ... @Dav, why?
J-P
@Dav: There's no reason to do that. Function declarations take effect before the step-by-step code in the same scope.
T.J. Crowder
+4  A: 

Yep. You want setInterval:

function myMainLoop () {
  // do stuff...
}
setInterval(myMainLoop, 30);
Brian Campbell
+1  A: 

Would this do?

setInterval(updateGameState, 1000 / 25);

Where 25 is your desired FPS. You could also put there the amount of milliseconds between frames, which at 25 fps would be 40ms (1000 / 25 = 40).

Tatu Ulmanen
you prolly want to pass the function, not its result
just somebody
You're right, fixed.
Tatu Ulmanen