• Home
  • blog
  • Quick Tip: How to Make a Game Loop in JavaScript

Quick Tip: How to Make a Game Loop in JavaScript

The “game loop” is a name given to a technique used to render animations and games with changing state over time. At its heart is a function that runs as many times as possible, taking user input, updating the state for the elapsed time, and then drawing the frame.

In this short article you’ll learn how this fundamental technique works and you’ll be able to start making your own browser based games and animations.

Here’s what game loop in JavaScript looks like:

function update(progress) {
  // Update the state of the world for the elapsed time since last render

function draw() {
  // Draw the state of the world

function loop(timestamp) {
  var progress = timestamp - lastRender


  lastRender = timestamp
var lastRender = 0

The requestAnimationFrame method requests that the browser call a specified function as soon as it can before the next repaint occurs. It’s an API specifically for rendering animations but you can also use setTimeout with a short timeout for a similar result. requestAnimationFrame is passed a timestamp of when the callback started firing, it contains the number of milliseconds since the window loaded and is equal to

The progress value, or time between renders is crucial for creating smooth animations. By using it to adjust the x and y positions in our update function, we ensure our animations move at a consistent speed.

Updating the Position

Our first animation will be super simple. A red square that moves to the right until it reaches the edge of the canvas and loops back around to the start.

We’ll need to store the square’s position and increment the x position in our update function. When we hit a boundary we can subtract the canvas width to loop back around.

var width = 800
var height = 200

var state = {
  x: width / 2,
  y: height / 2

function update(progress) {
  state.x += progress

  if (state.x > width) {
    state.x -= width

Drawing the New Frame

This example uses the <canvas> element for rendering the graphics but the game loop can be used with other outputs like HTML or SVG documents too.

The draw function simply renders the current state of the world. On each frame we’ll clear the canvas and then draw a 10px red square with its center at the position stored in our state object.

Continue reading %Quick Tip: How to Make a Game Loop in JavaScript%