Jerome Etienne Notes
Just released Pacmaze my first WebGL game! Check it out!

cancelRequestAnimationFrame() For Paul Irish requestAnimationFrame()


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.

Step 1: how to get the code

First include the cancelRequestAnimFrame() code in your page.

window.cancelRequestAnimFrame = ( function() {
    return window.cancelAnimationFrame          ||
        window.webkitCancelRequestAnimationFrame    ||
        window.mozCancelRequestAnimationFrame       ||
        window.oCancelRequestAnimationFrame     ||
        window.msCancelRequestAnimationFrame        ||
} )();

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);

Step 2: how to use it

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(){
  request = requestAnimFrame(animloop, element);

// cancelRequestAnimFrame to stop the loop in 1 second
}, 1*1000)

About requestAnimationFrame

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.

Follow jerome_etienne on Twitter