What Are The Differences Between Setinterval And Requestanimationframe?
Solution 1:
The requestAnimationFrame
method is used to sync animations with the screen updates. The screen updates at a specific rate, for example 60 times per second. If you sync your animation updates so that they occur at that rate, the animation will look smooth.
Here is an example, where anim1
runs at the rate of the screen, while anim2
runs at a fixed rate. If you run the demo, you see that the left square moves smoothly, while the right square jumps a bit in the movement.
You can make the setInterval
run more often to make it a bit smoother, but to make it support all different screens you would have to make it run faster than 120 times per second, which uses a lot more CPU than needed for most screens, and some browsers doesn't even support a rate that fast.
window.requestAnimationFrame(anim1);
window.setInterval(anim2, 25);
var a1 = document.getElementById('a1');
var a2 = document.getElementById('a2');
var t2 = 0;
functionanim1(t1) {
a1.style.left = (50 + Math.cos(t1 / 500) * 30) + 'px';
a1.style.top = (50 + Math.sin(t1 / 500) * 30) + 'px';
window.requestAnimationFrame(anim1);
}
functionanim2() {
a2.style.left = (100 + Math.cos(t2) * 30) + 'px';
a2.style.top = (50 + Math.sin(t2) * 30) + 'px';
t2 += 0.055;
}
Demo: http://jsfiddle.net/qu2Dc/2/
Note some differences:
anim1
callsrequestAnimationFrame
to catch the next update.anim1
gets a parameter to use for timing, whileanim2
uses a counter.
Also, note that setInterval
is supported in all browsers, but requestAnimationFrame
is not. Internet Explorer 9 for example does not support it. If you plan to use it, it would be a good idea to check if it exists first, and use setInterval
as a fallback.
Solution 2:
From MDN:
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes as an argument a callback to be invoked before the repaint.
Use the latter for animation and the former any time you want to call a function at a specified interval.
Post a Comment for "What Are The Differences Between Setinterval And Requestanimationframe?"