Using setTimeout() instead of setInterval()
One thing you should always remember about using setInterval: if we set number of milliseconds at – let’s say 20ms – it will call our game loop function EACH 20ms, even if the previous one is not yet finished. This may lead to many problems (incomplete rendering, etc.).
That’s where we can use another function:
- Syntax: setTimeout(function, ms);
This function works like setInterval(…) with one difference: it calls your function ONCE and AFTER a given amount of time.
EXAMPLE OF THE MONSTER ANIMATED IN A CANVAS WITH SETTIMEOUT
PROBLEMS WITH SETINTERVAL() AND SETTIMEOUT()
This problem also occurs with setInterval, the timing is not “very” reliable. If you plan to run a function every 20ms, and if you measure precisely the real timing, sometimes you will discover big differences between what is scheduled and what is performed. This is because these methods were designed a long time ago, when high precision timers and 60 frames per second animation were not an option.
Here comes the requestAnimationFrame API, a very good companion to the canvas API!