HTML5 game pases when you go to another tab

I'm making a simple game and I use requestAnimationFrame. Now the problem is that each I change to another tab the game pauses and when I return the game continues.

This is really bad because the game is multiplayer and restarting the game each time a user switches to another tab doesn't seem like a great idea.

Do any of you have any idea how I can keep the game active, while the user change to another tab?

Thanks.

• Have you searched online about this? As far as I know it's a quite common issue. Would this help? – TomTsagk Sep 27 '18 at 15:04
• @TomTsagk That question is unanswered! – Philipp Sep 27 '18 at 15:17
• @Philipp Oops didn't notice that, however one of the comments specifies why requestAnimationFrame is not working and setTimeout should work. – TomTsagk Sep 27 '18 at 15:21

Put the logic code into a function which you execute at regular intervals with SetInterval. Intervals still get executed when the tab is inactive. Note that if you use SetInterval on the main window object, then most browsers will throttle it when the tab is inactive. When you are using a game loop with a variable time-step (you check how much time elapsed since the last update and take it into account when moving things) then this should not be a problem. But if you want to use a fixed timestep, then you can get around this by using a web worker. Web workers can use intervals which do not get throttled in inactive tabs.
Your drawing code should stay in the method you pass to requestAnimationFrame. You can do canvas drawing in your interval method, but using requestAnimationFrame is recommended. It should be easier for the browser's rendering engine (whether this translates to a tangible performance benefit is implementation-specific) and there is little reason to waste the client's resources on drawing frames nobody is going to see.
• I experimented with this today and I made an event visibilitychange just to see whether my update func runs even in the background with setTimeout and it turns out it ran 17 times in 10 seconds which is not acceptable and pauses the game in the same way requestAnimationsFrame did - it seems for now the way to go would be a web worker. – CupOfCoffee Sep 29 '18 at 13:57