Read more

Stop animations and network polling when the document tab isn't visible

Henning Koch
July 28, 2016Software engineer at makandra GmbH

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?

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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 || document.visibilityState == 'visible') {
    // do expensive thing
  }
}

setInterval(5000, pulse);

Supported in real browsers and IE10 Show archive.org snapshot . The !document.visibilityState in the code above assumes that the page is visible in case you have an old IE.

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

Posted by Henning Koch to makandra dev (2016-07-28 16:32)