Jump to content
  • Advertisement
Sign in to follow this  

Make a Game Loop in JavaScript(P1)

This topic is 853 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

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

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

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!