I'm developing a browser game and am using the timestep implementation from the famous Fix your timestep! article.
It works perfectly, but there is one problem. If you tab out of the tab and then come back 5 minutes later or so, it freezes, because it has to execute all the missed physics calculations. That is, this code:
accumulator += frameTime;
while (accumulator >= dt)
{
previousState = currentState;
integrate( currentState, t, dt );
t += dt;
accumulator -= dt;
}
Seems to have to execute for quite a while because the accumulator has missed so many calculations while the tab was .. sleeping I guess?
I'm confused though. Shouldn't Javascript continue to run while the tab is not active? Why is this happening?
Is there any way to fix this? Ideally the Javascript would continue to run so that it wouldn't cause the tab to freeze for 2 minutes when coming back to it after being in other tabs for a while.
currentTime
minus theprevTime
to determine how many physics iterations to do. And because the current time "skips" from, say,t=1000
tot=61000
when you're gone for a minute, it thinks it has to perform 60 seconds worth of physics calculations. But that sounds.. correct..? I guess the main issue is that it seems like the Javascript isn't running when the tab isn't active. \$\endgroup\$requestAnimationFrame
? And that suspends while the tab is inactive? But other Javascript in other sections of the code might continue to run? Hmm, so how should I run the physics instead? I thinksetInterval
also has that behavior. Do I need to use WebWorkers or something? \$\endgroup\$setInterval
as described at the link above (which shows the calls are slowed when out of focus, not stopped likerequestAnimationFrame
). But we can eliminate the stall when regaining focus as I describe in the answer below. \$\endgroup\$