当标签处于非活动状态时,iOS 5会暂停JavaScript [英] iOS 5 pauses JavaScript when tab is not active

查看:151
本文介绍了当标签处于非活动状态时,iOS 5会暂停JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特定于iOS 5的问题,相同的代码适用于ios 4.X和其他桌面浏览器。



我使用JavaScript做一些事情秒,现在问题是当我切换到iPad safari中的另一个选项卡时,此脚本停止工作。



当我切换回此选项卡时,它再次开始工作。 / p>

您可以在此页面上重现它,
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_infinite



访问此链接,点击开始计数,然后转到其他浏览器标签。当你几秒钟后回到这个标签时,你会注意到标签没有激活时计数器没有增加。



<我认为Apple这样做是为了提高性能。有人可以建议一个解决方案,让它工作,我完全坚持这个问题?

解决方案

如果你有一个柜台,而不是比之前增加1秒,存储开始时间,然后计算自该开始时间以来的计数。你仍然会每秒都这样做,但它会从暂停期间恢复。

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

查看JS Fiddle的工作示例



更新



我刚刚在运行IOS5的iPad2上进行了测试,它肯定会暂停在非活动标签中执行JavaScript。您将无法阻止此行为,您只需使用它。



查看JS Fiddle上的测试页


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?

解决方案

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

这篇关于当标签处于非活动状态时,iOS 5会暂停JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆