setInterval function to schedule a function to draw the 3D scene so that it is called on a regular basis. This works well enough for simple demos, but has problems if generally used. If a page is loaded in your browser, even if it’s in a hidden tab or window,
setInterval keeps getting called. This means that having more than one or two WebGL pages loaded can make your machine bog down.
Luckily, the browser writers are well aware of this problem, and now WebKit (that is, Safari and Chrome) and Minefield both support a new function, officially called
requestAnimationFrame (it has slightly different names in different browsers right now, more on that later). This takes one parameter, a function which will be called when the browser thinks you should render your scene again. To use it, you just make your rendering function (
tick in most of my tutorials) finish with a call to
requestAnimationFrame to ask for itself to be called again next time a frame is needed, and then replace the call to
setInterval with an initial call to your rendering function to draw the first frame and schedule a callback for the next.
A few weeks ago, Gman suggested that I switch the tutorials over to using this pattern, which I’m in the process of doing. But in the meantime, I really recommend this article on how to use it (for animation in general, not just WebGL) from Paul Irish. You might also find this utility module from Google useful; among other things, right at the end of the file, it exposes the function in a cross-browser way, so that you don’t need to worry about the naming differences between Mozilla and WebKit.