Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

A simple requestAnimationFrame example visually explained

The reques­tAni­ma­tion­Frame func­tion lets you hook into ren­der cycle of the browser and spec­ify any changes that you want to make to your ele­ments before the re-render occurs. In this way, you essen­tially batch together the all the cal­cu­la­tion that the browser needs to per­form on a re-render in one call thereby improv­ing per­for­mance.

window.requestAnimationFrame

Here’show you would nor­mally add a func­tion invo­ca­tion to the reques­tAni­ma­tion­Frame event queue.

element.addEventListener('mousemove', function(){
    window.requestAnimationFrame(doSomeAnimation);
});

function doSomeAnimation(){
   //....
   //.... set some styles, animate something etc
   //.... 
}

requestAnimationFrame event queue

The prob­lem with the above code is that events like the mouse­move fire too often which means that this queue will grow quickly. More­over, you prob­a­bly don’t want a ren­der to occur as many times as the mouse­move event takes place.

For such cases, in order to opti­mize our code for the screen refresh rate, we need to make sure that we throt­tle the adding of a pend­ing invo­ca­tion to the queue by exam­in­ing if a pre­vi­ously added invo­ca­tion has been exe­cuted. We can do that eas­ily by set­ting and inspect­ing a flag.

var pendingAnimation = false;

element.addEventListener('mousemove', function(){
    // Only animate if there is no pending animation
    if(!pendingAnimation){
        pendingAnimation = true;
        window.requestAnimationFrame(doSomeAnimation);
    }
});


function doSomeAnimation(){
   //....
   //.... set some styles, animate something etc
   //.... 
   //Reset the flag
   pendingAnimation = false;
}

This time, since we only add another item to the queue if the flag has been cleared, we effec­tively add only one item to the queue no mat­ter how many times the mouse event fires.

To learn more about browser sup­port for this fea­ture see here.


Ryan Sukale

Ryan is a UX engineer living in San Francisco, California.

You may also like...