Skip to content Skip to sidebar Skip to footer

What Happens To Settimeout When The Window Is Out Of Focus?

I have a situation where I need to reauthenticate a token on a cordova app before the authentication token expires. To do that I figured I'd set a timeout just before the auth toke

Solution 1:

The timeout behavior really depends on the device type and OS version. On some, any timers that are "due" fire as soon as the application becomes active. On others (and I believe this is the case for current iOS), the timer is paused while your application is inactive and resumes when it becomes active.

For a long-running timer (i.e. your 4 hours example) you can't rely on the setTimeout() because on some devices it won't account for the inactive time. You'll need to subscribe to Cordova's resume event and re-calculate and update your timers. The following setLongTimeout() function should behave as expected in Cordoval. It's untested and would need to be expanded if you need multiple long timeouts.

var longTimeoutId, longTimeoutDate, longTimeoutCallback;

// Use instead of `setTimeout()` for a long timeout in CordovafunctionsetLongTimeout(callback, delay) {
    if (longTimeoutId) {
        clearTimeout(longTimeoutId);
    }

    longTimeoutCallback = callback;
    longTimeoutDate = Date.now() + delay;

    longTimeoutId = setTimeout(function() {
        longTimeoutId = null;
        callback();
    }, delay);
}

document.addEventListener("deviceready", function() {
    document.addEventListener("resume", function() {
        if (longTimeoutId) {
            setLongTimeout(callback, longTimeoutDate - Date.now();
        }
    });
});

Post a Comment for "What Happens To Settimeout When The Window Is Out Of Focus?"