What is Chromium's "Throttle Javascript timers in background" feature and how to handle it?

Viewed 1977

Since version 86 of Chromium, there is a new experimental feature called "Throttle Javascript timers in background" that is added to fix the high battery drain of Chromium browsers.

The description says:

In a Window whose top Window has been hidden for 5 minutes, timers can run:

  • aligned on 1-minute intervals, or,
  • if the Window is same-origin with the top Window, > 1 minute after the last timer has run in any Window in the tree that is same-origin with the top Window.

In a page that has been backgrounded for less than 5 minutes, keep the existing policy of aligning wake ups from timers on 1-second intervals.

Are they referring to the DOM functions setTimeout and setInterval? How exactly are those handled on these circumstances?

I imagine to have a setInterval for every 5 seconds that will be modified to 60 seconds as soon as the tab is hidden for 5 minutes. Doing the same for setTimeout might cause many jobs to run at the same time when returning to a tab. Skipping those could break logic, so simple job queues could cause other issues in the website.

So, how is the feature working, exactly? And, how can a developer make sure their logic won't break while the throttling is active?

1 Answers

It is what it says on the tin: background and hidden tabs don't get to run JS timers at high frequency. The shortest interval allowed becomes a full minute, so that your pages aren't burning through people's battery with code that's doing things that no one's even looking at.

The solution is to write proper page logic, and not run any code at all when no one's looking. This means having a blur and focus handler for your page so that your code can stop and resume things that need to run on timeouts or intervals. After all: if no one's looking, your page "needs" to do nothing, because the entire page is not needed.

Related