JavaScript Timers for Game Dev
(Almost) every game needs a game loop – and in order to create a game loop in HTML5 you are going to need to use a javascript timer. Why? Well because JavaScript is single threaded with the rest of the DOM, which means that if you are in a loop that never gives up control, the page will never update and you will stall out your players computer.
To get around this we use timers, which give control back to the browser but make sure our game loop gets called at regular intervals. Sounds simple, right? Well it isn’t exactly because we don’t have a whole lot control of the browser – the user may be playing our game or he may be off-page crunching a 100000 line spreadsheet. This is one of the downsides of browser-based games – we can’t count on having the computer’s attention. Throw into that variation in the different lower bounds for how often our functions can get called, we’re in for a little bit of pain.
Luckily people have been at this issue for a bit and the browser makers have helped us out by starting to implement a feature called ‘requestAnimationFrame’ which is synced with visual refreshing of the page.
To get a basic understanding of JavaScript timers – check out John Resig’s article from 2008. Once you’ve got that under your belt, check out Paul Irish’s article on shimming in support for requestAnimationFrame across the various browsers and Joe Lambert has a great article on using requestAnimationFrame as a drop in replacement for setTimeout / clearTimeout and setInterval / clearInterval.