Domanda

I am currently developing a peer to peer game in JavaScript using WebRTC. It treats one of the peers (i.e. the host) as the server and any other peers who join connect to the host through a node.js brokering server.

I am currently trying to solve an issue where the game stops updating for everyone if the host switches tabs such that the game is no longer the active tab. After doing some research, I discovered that this is because I'm using something like:

setTimeout(callback, 1000 / 60);

in my game loop. setTimeout (at least in Chrome and Firefox, which are the browsers I'm concerned with) is defined such that if the page calling it is not in your active tab, it can be called a maximum of once per second.

I read that Web Workers don't have this constraint, but in order to make that work I would need to run all of my game logic inside the web worker. I tried sending my game object to the worker using JSON.stringify(), but it said that the object had a circular reference (in the game loop) and it couldn't be converted to JSON. So I'm not sure what to do about that.

I also looked into implementing my own timer which kept running regardless of whether the page was in the active tab, but I'm not sure how to do this, either.

I don't really have a problem doing it either of these ways, or even some other way I haven't thought of yet, provided it doesn't incur a large performance overhead. Any suggestions would be greatly appreciated.

È stato utile?

Soluzione

So, as I said above, Web Workers are able to call setTimeout() without the 1 second delay for inactive tabs. My solution then was to create a Web Worker which was only responsible for calling setTimeout() (called in its onmessage event listener). Then, at the end of each game loop I called:

this.worker.postMessage(null)

It could be argued that it would be more efficient to give the Web Worker more responsibility than just calling setTimeout(), since I've already added the overhead of waiting for messages to be sent between the main thread and the worker. This is something I might look at in the future.

The main problem with doing it this way is compatibility with IE; IE did not get support for web workers until version 10.0. This isn't really a concern for me but I think it's worth mentioning.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top