在iPhone睡眠模式下运行计时器(没有JavaScript)?

问题描述:

据我今天所知,如果我将一部手机置于运行javascript计时器功能的睡眠模式,它将暂停.

So as I have learned today, if I put a phone in sleep mode that is running a javascript timer function, it will become paused.

由于我需要某个应用程序的计时器-它需要继续记录时间并显示时间,每秒更新一次元素的innerHTML:您认为我应该如何使该计时器工作?

As I need a timer for a certain application - that needs to continue to record the time and display it, updating the innerHTML of an element ever second: how do you think I should go about getting this timer to work?

感谢您的大力帮助!

var startTime;
var timer;

function displayTime() {
    var now = new Date();
    var timeDiff = new Date(now - startTime); // constructor uses UTC, so use UTC date functions from here on
    var hours = timeDiff.getUTCHours();
    var mins = (timeDiff.getUTCMinutes() < 10) ? '0' + timeDiff.getUTCMinutes() : timeDiff.getUTCMinutes();
    var secs = (timeDiff.getUTCSeconds() < 10) ? '0' + timeDiff.getUTCSeconds() : timeDiff.getUTCSeconds();
    document.getElementById('time').innerHTML = hours + ':' + mins + ':' + secs;
    if (hours >= 2) clearInterval(timer);
}

window.onload = function() {
    startTime = new Date();
    timer = setInterval(displayTime, 1000);
}

当手机唤醒并且应用返回到前台时, startTime 应该仍然是您开始计数的原始时间,因此您只需要知道现在和现在之间的时间差即可.无需在睡眠时更新显示;它只需要知道自原始开始时间起的时间即可.

When the phone wakes and the app goes back to foreground, startTime should still be the original time when you started counting, so you just need to know the diff between now and then. It doesn't need to update the display while asleep; it just needs to know the time since the original starting time.