Never use setTimout()!

I made an example which shows you should never use setTimout() or setInterval() in Phaser.

Link is here:

A while ago I figured out that you could use setTimeout instead of the built in Phaser timer to delay things. I decided to use it as at the time I saw no downside to it. I especially liked how simple it was compared to the Phaser Timer (I was learning at the time)

Well recently I made a rhythm game where timing matters a lot and I used setTimout().

I noticed that my game constantly jittered and stuttered. I could not figure out the solution to this until Phailser told me to use the Chrome profiler. I tried it and saw that setTimout was taking a lot of time. So, I decided to make an example to test my theory and it showed that setTimeout is really slow compared to the built in timer.

Many of you probably knew this, but I sure didn’t.

1 Like

Thanks for the info! In my game ([Phaser 3] Android game by newbie) i’ve used a lot of setTimeouts and game work little laggy on low-end and some mid-end smartphones. I will try to rewrite all the timers

Phaser aready has timer functions, so using those would be a better idea, I think.

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.


Great explanation.