Animation Loops using requestAnimationFrame

by kirupa   |   15 August 2013

In this short video, I continue my unhealthy obsession with the requestAnimationFrame function by summarizing what it does and the role it plays in animation loops.

Hit Play below to get the video rolling:

Example + Source Code

The example I show in the video is of the following sliding circle. The full source for it looks as follows:

<!DOCTYPE html>
<meta charset="utf-8">
<meta content="stuff, to, help, search, engines, not" name="keywords">
<meta content="What this page is about." name="description">
<meta content="An Interesting Title Goes Here" name="title">
<title>Something, something, sliding thing!</title>
<style type="text/css">
body {
	background-color: #FFF;
	margin: 30px;
	margin-top: 10px;
#contentContainer {
	width: 550px;
	height: 350px;
	border: 5px black solid;
	overflow: hidden;
	background-color: #FFFF00;
#thing {
	position: relative;
	left: 50px;
	top: 25px;

<div id="contentContainer">
	<img id="thing" alt="the thing" height="300" src="../../html5/images/donut.png" width="300">

<script src="//"></script>
var theThing = document.querySelector("#thing");
var currentPos = 0;

// depending on your browser, the right version of the rAF function will be returned...I hope
var requestAnimationFrame = window.requestAnimationFrame || 
							window.mozRequestAnimationFrame || 
							window.webkitRequestAnimationFrame || 
function moveThing() {
	currentPos += 5; = currentPos + "px";
	if (Math.abs(currentPos) >= 900) {
		currentPos = -500;


What you see in the video is me starting from an earlier version of this code and adding the relevant parts to setup our animation loop and get the animation rolling! 

Going Further

To learn more about requestAnimationFrame, check out the following tutorials:

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out


Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
new books - yay!!!