当用户切换到另一个应用或屏幕休眠时,计时器似乎会暂停,直到用户切换回应用(或屏幕唤醒时)。
Phonegap 有一个resume 事件,你可以收听而不是轮询状态(如果你想在它失去焦点之前做某事,还有一个pause 事件)。您在 deviceReady 触发后开始收听它。
document.addEventListener("deviceready", function () {
// do something when the app awakens
document.addEventListener('resume', function () {
// re-create a timer.
// ...
}, false);
}, false);
我将 Angular 与 phonegap 一起使用,并且我实现了一个服务,它为我管理一定的超时,但基本上你可以创建一个对象来设置计时器,取消计时器,最重要的是,更新计时器(更新是在'resume' 事件)。
在 Angular 中,我有一个范围和根范围,我可以将数据附加到,我的超时是全局的,所以我将它附加到根范围,但出于本示例的目的,我将简单地将它附加到文档对象。我不宽恕这种做法,因为您需要将其应用于某种范围或命名空间。
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;
}
}
};
};
您可以让管理器函数接受一个毫秒参数,而不是将其传递给 set,但这又在某种程度上模仿了我编写的 Angular 服务。操作应该足够清晰和简洁,以便对它们进行一些操作并将它们添加到您自己的应用中。
var timeoutCallback = function () { console.log('timer fired!'); };
var manager = timeoutManager();
manager.setTimer(20000);
一旦在事件侦听器中获得恢复事件,您将需要更新计时器,如下所示:
// do something when the app awakens
document.addEventListener('resume', function () {
var manager = timeoutManager();
manager.updateTimer();
}, false);
超时管理器还有cancelTimer(),可以用来随时杀死定时器。