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. Remove the blank value from a html select option dropdown
  2. Getting started with es6 iterators and iterables
  3. Generators and Yield in es6
  4. css: margin does not work
  5. Managing the browser navigation history using HTML 5 pushstate and popstate