Chrome and Firefox throttle setTimeout/setInterval in inactive tabs

March 1, 2012 Mark Rushakoff

Do your Jasmine tests (or anything else) seem to lock up when they aren’t the active tab in your browser?

Unfortunately, your new and modern browser is to blame. There are a few workarounds, but none of them are ideal in my opinion.

The cause of the problem

In early 2011, both Firefox and Chrome clamped the minimum wait time for setTimeout and setInterval to one second when running in a tab that is not the active tab for its window.

You might also be surprised to find out that HTML5 specifies a minimum of 4ms delay for setTimeout.

Workarounds

Workaround 1: Run that tab in its own window

This is the easiest solution, but it’s often less convenient to switch between browser windows when you want to just switch between tabs in the same window.

Workaround 2: Compensate for the fact that your callbacks will happen at most once per second

The accepted answer at this StackOverflow question demonstrates how you can figure out “where your animation is supposed to be” and just jump ahead. This workaround probably doesn’t apply if you have logic beyond visuals that depend on somewhat accurate timing.

Workaround 3: Use another, newer (and not necessarily standardized) API

window.postMessage

Mozilla suggests that you use window.postMessage to achieve sub-4ms delays.

window.setImmediate

Microsoft recommends using the setImmediate function as a replacement for setTimeout with a delay of 0.

But Mozilla has this to say about setImmediate:

This method is currently only proposed, is not expected to become standard, and is only implemented by recent builds of Internet Explorer.

On a side note, the Microsoft page has a lovely visualization of quicksort.

window.requestAnimationFrame

Another not-yet-standardized function, requestAnimationFrame seems best suited for animations, not for precise timing.

Workaround 4: Build your browser from modified source

I’m being somewhat facetious here, but Chrome and Firefox both have hardcoded constants for the interval limit. Without looking through the rest of the source code, I can’t conclusively say for either browser that there is no simple way to add support for overriding the inactive tab’s clamp value.

I saw one or two mentions about Firefox having an option to overwrite the minimum timeout limit, but since I’m not able to find those links again or any further information about those options, I’m led to believe that Firefox also does not let you override that one second minimum limit.

About the Author

Biography

Previous
Common iOS Gotchas
Common iOS Gotchas

Often enough, we find ourselves battling a problem that can sometimes seem to last forever and when we fina...

Next
Mobile Design Best Practices
Mobile Design Best Practices

… Read more