简体   繁体   中英

iPad JavaScript timer stop running detecting sleep mode

I am developing a web app (website) that is going to be bookmarked on the home screen it runs a timer/stopwatch but if you lock the iPad then it stops the JavaScript etc. What is the best way to detect when the iPad goes in to sleep mode/ awakens and also how to resume the timer?

I have tried events such as Blur, onload, onunload and also Visibility API any ideas?

I am using HTML5 so tried storing the timer value in local storage but unsure if this is the best approach any ideas or code examples..?

Thanks

The timer you're using is not a reliable timer (sorry Kelli)

If you look at the code it essentially does this:

var seconds = 0;
setInterval(function () {
    seconds += 1;
    console.log(seconds);
}, 1000);

setInterval and setTimeout are not reliable for timing . They can easily skew up to 100ms every tick. If JavaScript is very busy handling other events it can skew even more. If your browser sleeps your JavaScript event loop it will stop completely. You can not detect a resume and your timer is completely skewed.

To get around this, use a polling method using the native Date to measure time, only it is accurate.

// new Date creates a `Date` object with the current timestamp
var start = new Date(), now;
setInterval(function () {
    now = new Date(); // poll new current time
    console.log(now.getTime() - start.getTime());
}, 1000); // change to 100ms

There is one minor caveat: setInterval still skews. So you might see the time jump up by 2 seconds or 0 seconds every once in a while. To solve this, increase the number of times you poll, to like 100ms. Minor note: getTime measures in milliseconds, this is great for stop watches ;)


Using the polling method your timer will always be reliable. If you sleep and unsleep the timer will just resume. It will jump to the current time.

So long as you remember start you're good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM