Never use setTimout()!

I’ll try to explain why setTimeout causes these problems.

Phaser runs the game loop using the Request Animation Frame API, which allows it to sync the frame rate to the monitor’s refresh rate. However, if the game is inactive, a browser may throttle the game loop. This is one of the factors that can cause great fluctuations in the time elapsed between two frames (called the time delta). To avoid weird behavior, Phaser will smooth this delta and may even ignore the real value (for a limited number of frames) if it becomes too large. This is what allows the game to run smoothly under different circumstances.

The internal time-keeping systems (including the Clock, which keeps track of Timer Events) use the time delta (i.e. the time elapsed between two frames) to calculate their internal time. Depending on how the game is running, this time can be much different from the wall-clock time that setTimeout uses. This is why the delays it creates can feel so erratic since it can potentially go off at any time relative to the in-game time.

Another thing to keep in mind is that JavaScript is single-threaded. A long-running operation could delay a timeout from executing right when it’s supposed to. However, I’m not convinced this could have a perceivable effect.

6 Likes