开发者

Running Timer in iPhone Sleep mode (with no javascript)?

开发者 https://www.devze.com 2023-03-28 08:21 出处:网络
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.

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.

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

Thanks for the grand help!


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);
}

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号