Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

ipad - iOS 5 pauses JavaScript when tab is not active

I have a problem specific to iOS 5 and same code works in ios 4.X and other desktop browsers.

I am using JavaScript to do some stuff every few seconds, now the problem is when I switch to another tab in iPad safari, this script stops working.

When I switch back to this tab, it starts working again.

You can reproduce it on this page, http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_infinite

Visit this link, click on start counting, and go to some other browser tab.when you come back to this tab after few seconds you will notice counter did not increase when the tab was not active.

I think Apple has done this to improve performance. Can someone suggests a solution to make it work, I am totally stuck on this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a counter, rather than increment it by 1 ever second, store the "start time" and then calculate the count since that start time instead. You would still do this every second, but it would recover from a period of pausing.

<div id="counter"></div>
<script>
var startTime = new Date();

var updateCounter = function () {
    var displayArea = document.getElementById("counter");
    var currentTime = new Date.now();
    var differenceInSeconds = Math.round((currentTime - startTime) / 1000);
    displayArea.innerHTML = differenceInSeconds ;
}

window.setInterval(updateCounter, 1000);
</script>

See the working example on JS Fiddle

UPDATE

I have just tested on an iPad2 running IOS5 and it definitely pauses execution of JavaScript in inactive tabs. You won't be able to prevent this behaviour, you will just have to work with it.

View the test page on JS Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...