Paul Irish recently wrote requestAnimationFrame for smart animating. It is a polyfill so people can start use requestAnimationFrame() today and still be future proof.
This post is about its counterpart, cancelRequestAnimFrame(). It cancels a requestAnimationFrame(), like clearTimeout cancels a setTimeout.
First include the cancelRequestAnimFrame()
code in your page.
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
} )();
Add requestAnimFrame()
too. It is a slightly modified version of
paul's
to return setTimeout() handle.
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
return window.setTimeout(callback, 1000 / 60);
};
})();
Here is a possible way to use it. Show, dont tell, here is a live demo on jsfiddle
// to store the request
var request;
// start and run the animloop
(function animloop(){
render();
request = requestAnimFrame(animloop, element);
})();
// cancelRequestAnimFrame to stop the loop in 1 second
setTimeout(function(){
cancelRequestAnimFrame(request);
}, 1*1000)
In the past months, much has been done for web graphics. Among them, requestAnimationFrame() is used to make smoother animation while not wasting useless rescources when not visible. The spec is making good progress, and several implementations are already deployed.