Reputation: 71
I've been working on an idle/incremental game in my free time.
The main game loop function gets called many times a second using setInterval.
Since chrome (and probably other browsers) throttle function calls to 1 per second, my game loop doesn't properly update the right amount of times so now im looking into web workers.
After reading through the WebWorkers documentation on MDN, i still have a question on how to properly implement the web worker.
My current idea is to detect when the user swaps tabs (onblur
):
Would this be the right way to use the Web Worker?
Thanks!
-EDIT-
Some additional info, my game is an idle game similar to cookie clicker so there isnt any position tracking.
A very brief idea of something that is within my gameLoop
is a function call to gainResources(resourcePerSecond/gameTickRate)
.
Upvotes: 0
Views: 1201
Reputation: 11
My solution to stopping background tabs from throttling is to calculate the difference in time between each loop, and use that value to calculate how much things should've changed, assuming your loop updates things like resource amounts.
Example -
function loop() {
let now = Date.now();
let diff = now - Game.lastUpdate;
Game.lastUpdate = now;
// diff is now the exact amount of ms since loop has been called.
}
This way you are also sure to give an accurate production rate as setInterval doesn't call functions at exactly the same interval every time.
Upvotes: 1