JavaScript: Stopping expensive work in inactive tabs

Updated . Posted . Visible to the public. Repeats.

Is your application doing something expensive every few seconds? Maybe an animated slider that rotates images? Maybe you are updating data over the network every five minutes? It's a good idea to pause this if the your document tab is not even visible to the user. This saves your user's battery and data plan.

You can ask document.visibilityState Show archive.org snapshot whether this tab is visible:

function pulse() {
  if (document.visibilityState == 'visible') {
    // do expensive thing
  }
}

setInterval(5000, pulse);

You can also subscribe to the visibilitychange event Show archive.org snapshot to be notified if visibility changes.

What browsers do by default

Regardless of what you do in your own code, browsers will by default prevent inactive tabs from hogging too many resources:

  • In inactive tabs, timeouts and intervals are throttled to 1+ seconds
  • After a longer period of inactivity, some browsers will completely unload your tab, stopping any code that might still be running
Profile picture of Henning Koch
Henning Koch
Last edit
Henning Koch
Keywords
tab, window, background
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-07-28 14:32)