Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

FYI - iOS, JavaScript, and inactive tabs

DZone's Guide to

FYI - iOS, JavaScript, and inactive tabs

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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 incredible simple way to see this in action.

<!DOCTYPE html> 
<html>
<head>
  <title>Demo</title> 
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head> 

<body> 

<div id="test"></div>

<script>
var testdiv;
var x = 0;

document.addEventListener("DOMContentLoaded", init, false);
    
function init() {
    testdiv = document.querySelector("#test");

    window.setInterval(hb, 1000);
}

function hb() {
    x++;
    testdiv.innerHTML = "Called at "+(new Date()) + " and "+x;
}
</script>


</body>
</html>

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...

window.addEventListener("focus", function() {
  console.log("focus");
},false);

window.addEventListener("blur",function() {
  console.log("blur");
},false);

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

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}