在iPhone睡眠模式下运行计时器(没有JavaScript)? [英] Running Timer in iPhone Sleep mode (with no javascript)?

查看:58
本文介绍了在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.

这篇关于在iPhone睡眠模式下运行计时器(没有JavaScript)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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