What happens to JavaScript execution (settimeout, etc.) when iPhone/Android goes to sleep? What happens to JavaScript execution (settimeout, etc.) when iPhone/Android goes to sleep? ios ios

What happens to JavaScript execution (settimeout, etc.) when iPhone/Android goes to sleep?


Looks like Javascript execution is paused on MobileSafari when the browser page isn't focused. It also seems if setInterval() events are late, they are simply fired as soon as the browser is focused. This means we should be able to keep a setInterval() running, and assume the browser lost/regained focus if the setInterval function took much longer than usual.

This code alerts after switching back from a browser tab, after switching back from another app, and after resuming from sleep. If you set your threshold a bit longer than your setTimeout(), you can assume your timeout wouldn't finish if this fires.

If you wanted to stay on the safe side: you could save your timeout ID (returned by setTimeout) and set this to a shorter threshold than your timeout, then run clearTimeout() and setTimeout() again if this fires.

<script type="text/javascript">var lastCheck = 0;function sleepCheck() {        var now = new Date().getTime();        var diff = now - lastCheck;        if (diff > 3000) {                alert('took ' + diff + 'ms');        }        lastCheck = now;}window.onload = function() {        lastCheck = new Date().getTime();        setInterval(sleepCheck, 1000);}</script>

Edit: It appears this can sometimes trigger more than once in a row on resume, so you'd need to handle that somehow. (After letting my android browser sleep all night, it woke up to two alert()s. I bet Javascript got resumed at some arbitrary time before fully sleeping.)

I tested on Android 2.2 and the latest iOS - they both alert as soon as you resume from sleep.


When the user switches to another app or the screen sleeps, timers seem to pause until the user switches back to the app (or when the screen awakens).

Phonegap has a resume event you can listen to instead of polling for state (as well as a pause event if you want to do things before it is out of focus). You start listening to it after deviceReady fires.

document.addEventListener("deviceready", function () {    // do something when the app awakens    document.addEventListener('resume', function () {        // re-create a timer.        // ...    }, false);}, false);

I use angular with phonegap and I have a service implemented that manages a certain timeout for me but basically you could create an object that sets the timer, cancels the timer and most importantly, updates the timer (update is what is called during the 'resume' event).

In angular I have a scopes and root scope that I can attach data to, my timeout is global so I attach it to root scope but for the purpose of this example, I'll simply attach it to the document object. I don't condone that because you need should apply it to some sort of scope or namespace.

var timeoutManager = function () {    return {        setTimer: function (expiresMsecs) {            document.timerData = {                timerId: setTimeout(function () {                    timeoutCallback();                },                expiresMsecs),                totalDurationMsecs: expiresMsecs,                expirationDate: new Date(Date.now() += expiresMsecs)            };        },        updateTimer: function () {            if (document.timerData) {                //                //  Calculate the msecs remaining so it can be used to set a new timer.                //                var timerMsecs = document.timerData.expirationDate - new Date();                //                //  Kill the previous timer because a new one needs to be set or the callback                //  needs to be fired.                //                this.cancelTimer();                if (timerMsecs > 0) {                    this.setTimer(timerMsecs);                } else {                    timeoutCallback();                }            }        },        cancelTimer: function () {            if (document.timerData && document.timerData.timerId) {                clearTimeout(document.timerData.timerId);                document.timerData = null;            }        }    };};

You could have the manager function take a millisecond parameter instead of passing it into set, but again this is modeled somewhat after the angular service I wrote. The operations should be clear and concise enough to do something with them and add them to your own app.

var timeoutCallback = function () { console.log('timer fired!'); };var manager = timeoutManager();manager.setTimer(20000);

You will want to update the timer once you get the resume event in your event listener, like so:

// do something when the app awakensdocument.addEventListener('resume', function () {    var manager = timeoutManager();    manager.updateTimer();}, false);

The timeout manager also has cancelTimer() which can be used to kill the timer at any time.


You can use this class github.com/mustafah/background-timer based on @jlafay answer , where you can use as follow:

coffeescript

timer = new BackgroundTimer 10 * 1000, ->    # This callback will be called after 10 seconds    console.log 'finished'timer.enableTicking 1000, (remaining) ->    # This callback will get called every second (1000 millisecond) till the timer ends    console.log remainingtimer.start()

javascript

timer = new BackgroundTimer(10 * 1000, function() {    // This callback will be called after 10 seconds    console.log("finished");});timer.enableTicking(1000, function(remaining) {    // This callback will get called every second (1000 millisecond) till the timer ends    console.log(remaining);});timer.start();

Hope it helps, Thank you ...