Be the first user to complete this post

  • 0
Add to List

A simple requestAnimationFrame example visually explained

The requestAnimationFrame function lets you hook into render cycle of the browser and specify any changes that you want to make to your elements before the re-render occurs. In this way, you essentially batch together the all the calculation that the browser needs to perform on a re-render in one call thereby improving performance.
window.requestAnimationFrame Here'show you would normally add a function invocation to the requestAnimationFrame event queue.
element.addEventListener('mousemove', function(){
    window.requestAnimationFrame(doSomeAnimation);
});

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

requestAnimationFrame event queue
The problem with the above code is that events like the mousemove fire too often which means that this queue will grow quickly. Moreover, you probably don't want a render to occur as many times as the mousemove event takes place. For such cases, in order to optimize our code for the screen refresh rate, we need to make sure that we throttle the adding of a pending invocation to the queue by examining if a previously added invocation has been executed. We can do that easily by setting and inspecting 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 effectively add only one item to the queue no matter how many times the mouse event fires. To learn more about browser support for this feature see here.



Also Read:

  1. sessionStorage vs localStorage vs cookie applications
  2. Difference between async and defer attributes in script tags
  3. Error: can not find module 'underscore'
  4. imperative vs declarative/functional programming
  5. position: relative