This article looks at two basic ways to create a basic animation loop.

Example Details

The example will look at moving a rectangle on a webpage from left to right.

  • 60 fps frame rate
  • Move 1 pixel per frame
  • Go from 0 to 400px

Here is a Code Pen with the code.

See the Pen setTimeout vs requestAnimationFrame by Jonathan klughertz (@klugjo) on CodePen.

Using set Timeout

The first way of creating the loop that comes to mind is to use window.setTimeout and call a function every 1/60th of a second to achieve 60fps.

Here is the gist:

window.setInterval(() => {
// updateUI();
}, 1000 / 60);

The updateUI function will be responsible for updating the CSS.

Here is the full code to move a DOM element around.

const refreshRate = 1000 / 60;
const maxXPosition = 400;
let rect = document.getElementById('rect0');
let speedX = 1;
let positionX = 0;

window.setInterval(() => {
positionX = positionX + speedX;
if (positionX > maxXPosition || positionX < 0) {
speedX = speedX * (-1);
}
rect.style.left = positionX + 'px';
}, refreshRate);

Using request Animation Frame

Another and cleaner way of creating a game loop is to use the requestAnimationFrame built in function.

requestAnimationFrame will call the next frame and will need to be called recursively once the UI has been updated.

Here is the gist:

function step() {
// UpdateUI();
window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);

And here is the full code to move a DOM element around:

const refreshRate = 1000 / 60;
const maxXPosition = 400;
let rect = document.getElementById('rect1');
let speedX = 1;
let positionX = 0;

function step() {
positionX = positionX + speedX;
if (positionX > maxXPosition || positionX < 0) {
speedX = speedX * (-1);
}
rect.style.left = positionX + 'px';
window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);