requestAnimationFrame: Video Introduction to New Animation Techniques

The arrival of requestAnimationFrame gives browsers the ability to throttle animations to save them from devouring system resources, especially when they aren’t actually being shown on the screen. Knowing this, we need to learn how to use it and then actually start utilizing this new tool for the benefit of our users. For this very reason, I decided to make this short video tutorial explaining how requestAnimationFrame can be used in the animations on your applications.

In my previous post, I introduced you to what requestAnimationFrame is and how it differs from setTimeout and setInterval. Now you’ll get to see it in action:

Final Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Properties
var ball = $('#ball');
var distance = 800;
var time = 3;
var fps = 5;
var speed = distance / time / fps;
var startTime = new Date().getTime();

// Animation
function draw() {
var currTime = new Date().getTime();
var ms = currTime - startTime;
var pos = distance / (time * 1000) * ms;
pos = Math.min(distance, pos);

ball.css('left', pos + 'px');

if (pos < distance) {
setTimeout(function() {
window.requestAnimationFrame(draw);
}, 1000 / fps);
} else {
var endTime = new Date().getTime();
console.log(endTime - startTime);
}
}

draw();

End Animation

I hope you all learned at least a little bit about requestAnimationFrame API and animations in general. For the most part, things don’t really change much when switching from setTimeout, which is part of the point. The new requestAnimationFrame isn’t designed to change your code a lot; it’s designed to change the performance of your code. Anyway, thanks for watching and Happy Coding!

Author: Joe Zimmerman

Author: Joe Zimmerman Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.