Tuesday, April 12, 2011


On the suggestion of @mrdoob today I reworked the animation loops for my Quake 3 and Doom 3 demos to use requestAnimationFrame (if it's available). This won't really produce a visible difference for most people, but it should utilize the browser event loop more efficiently. Paul Irish gives a good explanation of it at his blog.

A side effect of this that may be of interest to other developers is the simple little jQuery plugin I wrote to support this functionality in a cross platform manner that also provides a few perks to the user. You use it like so:

$('#canvas').requestAnimation(function(event) {
    // Draw frame here...

The "event" passed into the callback function contains the following values:

timestamp: Current timestamp, equivalent to new Date().getTime()
elapsed: Milliseconds elapsed since the animation started
frameTime: Milliseconds elapsed since the callback was last called
framesPerSecond: Rough count of the number of times the callback has been called over the last second. Only updates once per second.

If you wish to stop animating, return false from your callback.

I recognize that this may not meet everyone's needs, and probably is a little buggy at the moment, but it should provide a quick and easy way to do a basic animation loop in a way that plays well with your browser. If you have any suggestions for improving it let me know!