FYI - iOS, JavaScript, and inactive tabs

This post is more than 2 years old.

This is something I had heard before, but didn't really think about it until a reader I was helping ran into it. It involves Safari on iOS (and I believe just iOS 5 and higher). If you have a web page using timed JavaScript (for example, a setInterval), and switch to another tab (or another app), then the operating system will pause the JavaScript environment. Here is an incredibly simple way to see this in action.

The code simply updates a div with a timestamp and an incrementing value. If you open this in your web browser on an iDevice, note the current value, and switch over to another tab, you'll see when you come back that the page had been paused in the background.

I tried to get around this by adding a focus/blur event handler to my code...

Which didn't work either since, hello, you can't run a JavaScript event handler when all of JavaScript is paused! So much for me being clever.

Anyway, there is a much simpler way around this. Check out this solution from StackOverflow: Handling standby on iPad using Javascript

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA

Archived Comments

Comment 1 by Simeon Bateman posted on 1/22/2013 at 11:25 PM

Hey Ray,

Mobile safari has pagehide and pageshow events for helping deal with this. I don't think it works for going between tabs, but it should help when going between apps.

Comment 2 by Raymond Camden posted on 1/22/2013 at 11:26 PM

Oh yeah? Let me test. I think you are wrong. If I'm wrong, I'll just delete this comment and it will be like I never doubted you.

Comment 3 by Raymond Camden posted on 1/22/2013 at 11:34 PM

That works - but - you would have to use the same technique as described in the SO article. Ie, given that I know how long I was gone, what did I miss?

Comment 4 by Simeon Bateman posted on 1/22/2013 at 11:37 PM

I guess it kinda depends on how you setup your loop. If your loop is really do this every 10 seconds then you need the heartbeat.

If the loop triggers every 10 seconds and your code says do what ever I need to since the last time I did it, then the events for show hide may be enough.

But isn't that the quintessential answer: "It depends!" :)

Comment 5 by Raymond Camden posted on 1/22/2013 at 11:38 PM

Agreed. And more options == more gooder. Thanks for sharing this. (Of course, the best solution, probably, would be the Page Visibility API!)