How to Create an Animation Loop in Your HTML5 Game
Here’s some code that simply counts ten times a second:
The process is straightforward, and you can use it any time you want something to happen at regular intervals:
Create a function that will be repeated.
In this simplistic example, the function count() will be called ten times per second.
In your initialization code, call setInterval().
This will set up the repeated call to the function.
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.
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.