Ask coding questions

← Back to all posts
requestAnimationFrame and setInterval are affected when window is hidden
HackingGo306 (36)

requestAnimationFrame and setInterval/recursive setTimeout are affected when the browser tab is hidden

When you run a program that uses requestAnimationFrame and switch to another tab so that you cannot see it, requestAnimationFrame stops.
Run the program below and switch to another browser tab, requestAnimationFrame will freeze completely and setInterval will fire every 1 second.
This shouldn't be a problem in single-player games, but in multiplayer games using node.js, it becomes a huge problem.

Are there any methods to allow graphics to run in the background?

Answered by xxpertHacker (935) [earned 5 cycles]
View Answer
Comments
hotnewtop
xxpertHacker (935)

Background tabs have their timers throttled. This feature ships in stable without a way to disable it.

Some people gave their workarounds on SO: https://stackoverflow.com/questions/6032429.

HackingGo306 (36)

@xxpertHacker
It seems like Web Workers is what I need, but they're a little confusing, do you have an example of those?

xxpertHacker (935)

@HackingGo306 Workers are just pieces of JavaScript that have their own globalThis objects, and communicate through messages globaThis.postMessage(...).

You'll really have to do some research yourself and get some hands-on experience though.
Some MDN URLS:

Coder100 (18071)

no, in fact multiplayer games most of them won't do anything about this, because it won't affect them!

the events will just not happen when you want them to, but they will still happen soon enough, just like irl!

HackingGo306 (36)

@Coder100
Wait what...?
That means I'm using socket.io wrong. It couldn't find a site that tells you how to structure a multiplayer game. Can you help?

Coder100 (18071)

well
here's how it roughly goes:

server --> player data --> [internet and other interference] --> client
server <-- player data <-- [internet and other interference] <-- client

@HackingGo306

HackingGo306 (36)

@Coder100
If I'm getting that right, then it should be like an imaginary chatbox?
In other words, the client sends data to the server which sends it to other players?

HackingGo306 (36)

@Coder100
But wouldn't that cause problems? If player A fires a bullet and then they freeze the graphics by going to another browser tab, the bullets aren't synced.

Coder100 (18071)

no
because
remember
that doesn't mean the server is out of sync with how global it is @HackingGo306

Coder100 (18071)

remember how games sometimes lag? This is why @HackingGo306

HackingGo306 (36)

@Coder100
What do you mean by 'global'?