Be the first user to complete this post
|
Add to List |
A simple requestAnimationFrame example visually explained
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
//....
}
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;
}
Also Read:
- Remove the blank value from a html select option dropdown
- Getting started with es6 iterators and iterables
- Generators and Yield in es6
- css: margin does not work
- Managing the browser navigation history using HTML 5 pushstate and popstate