问题描述
我的秒表脚本在Android的后台运行无瑕疵(计数时间),但iOS 4.3.2似乎暂停脚本。在iOS上,秒表在应用程序发送到后台时停止。
My stopwatch script runs flawlessly in the background on Android (counting up the time), but iOS 4.3.2 seems to pause the script. On iOS the stopwatch stops at the time where the application was sent to background.
我需要一个runnning秒表(时间在视图中每秒更新一次)
I need a runnning stopwatch (the time appears updated each second in the view) and some alarm messages in defined points in time.
秒表的代码如下:
this.timer = window.setInterval(function(){
instance.runtime += Stopwatch.INCREMENT;
instance.doDisplay();
}, Stopwatch.INCREMENT);
我知道原生解决方案,但是想要坚持使用JavaScript解决方案跨平台兼容性。
I'm aware of native solutions, but would like to stick with a JavaScript solution for the sake of cross-platform compatibility.
推荐答案
由于setIntervals在后台不工作,我将使用递归setTimeout。 >
这意味着你不能用+ =来跟踪时间,所以你需要使用一个(new Date).getTime();或Date.now()。
Since setIntervals don't work in the background I'd use a recursive setTimeout instead.
Which means you can't keep track of time with a +=, so you'll need to use a (new Date).getTime(); or Date.now() instead.
this.timer = function myTimer () {
instance.currentTime = (new Date).getTime();
instance.doDisplay();
setTimeout( myTimer, Stopwatch.INCREMENT );
}
如果setTimeout没有回到生活,更容易重新启动。
If the setTimeout doesn't come back to life when the app does it should be simpler to restart.
这篇关于如何在iPhone上的Phonegap运行背景JavaScript - 定时器/秒表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!