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:
- es6 iterators and iterables - creating custom iterators
- Applying floats and clearfix to block elements
- position:absolute
- Making max width work in internet explorer
- gzip compress and cache api response in express