Handling standby on iPad using Javascript

I agree that there really ought to be some signal you can hook on to to know when an application goes to sleep and when it wakes up, but you should be able to figure out when Safari wakes up indirectly.

When the webview goes into the background, Safari puts everything in it to sleep. It pauses any video, defers network request, stops updating the UI and pauses all setInterval/setTimeout operations. JS itself will never be aware (as far as I can tell) how these things happened, but it can tell that it has happened. The simplest way to use this is to build a regularly invoked method and check to see if it’s been an unexpectedly LONG time since the last update. If you expect something to update every 10 seconds and it’s been five minutes, you can be fairly sure that the device has woken up. Here’s a quick example I thought up:

    var intTime = new Date().getTime();
    var getTime = function() {
        var intNow = new Date().getTime();
        if (intNow - intTime > 1000) {
            console.log("I JUST WOKE UP")
        }
        intTime = intNow;
        setTimeout(getTime,500);
    };
    getTime();

This will detect when the user has returned from another tab, has dismissed the developer console or brought back Safari from the background. I’ve set the interval at half a second; you could set it at anything you need, though I think very low values will have concurrency issues and probably will burn the battery down on the device unnecessarily.

Leave a Comment