There are a ton of great posts out there about using RequestAnimationFrame (RAF) for your animation/game loops. These posts will quickly show you how to setup the RAF shim for cross browser support and then how to kick off the whole thing. See below
// RequestAnimationFrame Shim
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
// END RAF Shim
// Fire off our RAF loop
function animate(){
requestAnimationFrame( animate );
render();
}
To Infinity and Beyond
The previous code will get us started with an animation loop. Unfortunately the way a RAF loop works is to create a loop that will recursively call itself forever. If that is what you are going for then great. But if you want control of RAF what we need is a way to stop the animation loop when we are no longer animating. Enter CancelAnimationFrame.
Why are we stopping?
Before we talk about CancelAnimationFrame we should back up and talk about why you would want to start and stop the animation loop. The reason is simple. If our content isn't changing then why waste the time computing the RAF loop
This especially becomes a factor on devices that run on battery such as tablets and smartphones. Additionally, if we are using PhoneGap we will probably want to cancel the RAF loop when our app goes into the background with the "pause" event.
CancelAnimationFrame
To cancel a requestAnimationFrame we need to know the id. If you notice from our shim above the requestAnimationFrame function returns an id each time. We can easily adjust our animation loop to store this id so that we can cancel it later. We do this by passing the frame id to cancelAnimationFrame. Pretty simple.
// Store our frame id
var frame;
function animate() {
frame = requestAnimationFrame( animate );
render();
}
function cancel() {
cancelAnimationFrame( frame );
}
