Material

Game loops in JavaScript

I'm learning JavaScript! I mean, I already wrote some crap in it before, but now I'm learning enough to write something substantial. Like a (non-Perlenspiel) game.

One of the things you need for a game is a game loop. In large games these are increasingly tricky affairs spread out over multiple threads and designed to optimize memory access patterns. In JavaScript, you can't do that, but you can at least implement the basics correctly. The canonical tutorial on this stuff is deWiTTERS Game Loop which goes over several implementation strategies. Only one of those implementations, "Constant Game Speed independent of Variable FPS," is worth pursuing. (To know why, read the article.) So how to do it in JavaScript?


This post used to be a lot longer and full of bad advice. Here is good advice: Use only requestAnimationFrame. Just do everything the deWitters article says inside of requestAnimationFrame. After more testing I've discovered browsers' schedulers are basically awful, unreliable, and this is the only way to make a main loop appropriate for a game. If you are targeting one specific version of one browser on one platform, you can maybe manage a better loop with the setInterval-based method I had described before, but if you're doing that you're better off writing a native application in the first place.