How to Create an Animation Loop in Your HTML5 Game - dummies

How to Create an Animation Loop in Your HTML5 Game

By Andy Harris

If the canvas defines the space in an HTML5 game, an animation loop defines time. Most JavaScript games use a mechanism called setInterval() to cause repeated behavior. This function takes two parameters: a function name and a delay value.

Here’s some code that simply counts ten times a second:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
 <meta charset="UTF-8">
 <title>counting.html</title>
 <script type="text/javascript">
 var counter = 0;
 var output;
 function init(){
  output = document.getElementById("output");
  setInterval(count, 100);
 }
 function count(){
  counter++;
  output.innerHTML = counter;
 }
 </script>
</head>
<body onload = "init()">
 <div id = "output">
  nothing here yet
 </div>
</body>
</html>

The process is straightforward, and you can use it any time you want something to happen at regular intervals:

  1. Create a function that will be repeated.

    In this simplistic example, the function count() will be called ten times per second.

  2. In your initialization code, call setInterval().

    This will set up the repeated call to the function.

  3. Indicate the function that will repeat.

    The first parameter is the name of the function that will be repeated. Note that because you’re treating the function as a variable, you do not include parentheses with the function name.

  4. Indicate the delay.

    The second parameter is a delay value in milliseconds (a millisecond is 1/1000th of a second). This example runs at a delay of 100 milliseconds, which is 10 frames per second. The simpleGame library runs at 20 frames per second.

In simpleGame, when you create a Scene class, in addition to setting up a canvas, you’re also, via the Scene class, creating an interval that repeatedly calls the update() method of your game. This is why you need to have an update() method.