What happens to setTimeout when the window is out of focus?

戏子无情 提交于 2021-01-27 06:41:54

问题


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 token expires, to reauthenticate.

function authenticate() {
  var token = ... get token

  setTimeout(function() {
    .. try to reauthenticate
  }, token.expiresIn - 600*1000);
}

Problem I could see is that-

  1. The timeout period passes while the app is sleeping. Function does not fire?

  2. The timeout "countdown" (if that's how it works) is paused while the app is sleeping.

Neither of these are good scenarios. So my question is, what happens to a timeout while the application is out of focus? Should I instead have a 10 second interval that checks the expiration for this scenario?

Edit:

So lets say the token is for 4 hours. If the user uses the app for an hour, minimizes it for 2 hours and comes back, will the function call in an hour or 3 hours? This would be the point of the interval, so I can check the situation relatively quickly.


回答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 Cordova
function setLongTimeout(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();
        }
    });
});


来源:https://stackoverflow.com/questions/36317702/what-happens-to-settimeout-when-the-window-is-out-of-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!