1

I've got a page that shows real-time statistics. It runs a lot of javascript, makes a lot of HTTP requests, renders SVG charts every few seconds using D3.js, has a lot of CSS animations, and rearranges the DOM frequently.

As long as the page is focused, it runs smoothly. If I switch to another tab and come back later, there's often a short pause where the page seems to be frozen before the view suddenly seems to rerender and the page becomes usable again. The longer the tab has been backgrounded, the longer this pause is. If the tab has been in the background for a very long time (hours) and I switch back to it, it will be frozen for a long time then crash.

All these behaviors are observed in Chrome. I haven't tested much in other browsers.

What is Chrome doing during that pause when I first switch back to the tab?

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
  • possible duplicate of [Javascaript tasks Chrome is suspending when a tab is switched to backgrounded](http://stackoverflow.com/questions/13408597/javascaript-tasks-chrome-is-suspending-when-a-tab-is-switched-to-backgrounded) – Jonathan Lonowski Nov 16 '12 at 00:37

1 Answers1

2

You're running a setInterval or a series of setTimeouts.
Each one is queued up to run AFTER the point you specify in the function.

Google throttles everything on your page down to a few updates every second... ...so if you've got timers set to move things around and animate at 30fps or whatever, then you've got Google firing one round of updates (whatever you have scheduled), which will undoubtedly call something requesting another update, which will request another one...

...when you switch back, you've got hundreds (or tens of thousands) of these updates waiting to happen, and now instead of happening at 30fps, you have a bunch of these things waiting... all of them have passed their "do not run until..." time, and they're all going to try to update as fast as physically possible, until you get caught up to where the timer is current again.

If the browser supports the components of the page-visibility API, then pause your calls when the page is not visible.

if (!document.hidden) { doStuff(); }

OR

document.addEventListener("visibilitychange", function (evt) {
    if (evt.visibilityState === "hidden") { myApp.pause(); }
    else if (evt.visibilityState === "visible") { myApp.resume(); }
});

If it doesn't support the API, then you can try to polyfill it, using window.onblur, or otherwise.
That said, chances are if the browser doesn't support the page-visibility API, it also doesn't do hardcore throttling of the page-code.
That's not a 100% guarantee, but rather a semi-likelihood.

Norguard
  • 26,167
  • 5
  • 41
  • 49
  • For some reason, my question got duplicated when somebody edited it: http://stackoverflow.com/questions/13408597/chrome-tab-crashing-hanging-after-brought-on-foreground-being-long-time-on-bac – Trevor Dixon Nov 29 '12 at 23:58