【发布时间】:2020-07-10 14:33:00
【问题描述】:
我需要一个计时器,它应该在达到特定用户设置值后发出通知(我使用的是一个信号 API 通知)。
例如,如果用户将值设置为 7 分钟,则计时器应在 7 分钟后发送通知。用户可以设置的时间范围为 1-59 分钟。但即使使用后台模式插件 (https://github.com/katzer/cordova-plugin-background-mode),我也无法让 setInterval/setTimeout 函数在 5 分钟后工作。
尝试使用递归 setTimeout 方法:
function startTimerCounter() {
this.timerCounter = 0;
const objThis = this; //store this.
if (this.timerCounter >= this.setTime) {
this.backgroundMode.disable();
this.goalTimerReached = true;
} else {
this.backgroundMode.enable();
this.timer = setTimeout(function request() {
if (objThis.timerCounter === objThis.setTime) {
//onesignal notification
clearTimeout(objThis.timer);
} else {
++objThis.timerCounter;
objThis.timer = setTimeout(request, 1000);
}
}, 1000);
}
}
尝试使用 setInterval 方法:
function startTimerCounter() {
this.timerCounter = 0;
const objThis = this; //store this.
if (this.timerCounter >= this.setTime) {
this.backgroundMode.disable();
this.goalTimerReached = true;
} else {
this.backgroundMode.enable();
this.timerCounter = 0;
const objThis = this; //store this.
this.timer = setInterval(() => {
if (objThis.timerCounter === objThis.setTime) {
//onesignal notification
clearInterval(objThis.timer);
} else {
++objThis.timerCounter;
}
}, 1000);
}
}
顶部的后台激活通知,我可以看到后台模式处于活动状态。但是 5 分钟后计时器似乎没有运行。
知道如何解决这个问题吗?
***更新****
尝试在后台每 4 分钟调用一次函数以继续运行,但这对我不起作用:
function startTimerCounter() {
this.timerCounter = 0;
const objThis = this; //store this.
if (this.timerCounter >= this.setTime) {
this.backgroundMode.disable();
this.goalTimerReached = true;
} else {
this.backgroundMode.enable();
this.timerCounter = 0;
const objThis = this; //store this.
this.timer = setInterval(() => {
if (objThis.timerCounter === objThis.setTime) {
//onesignal notification
clearInterval(objThis.timer);
} else {
++objThis.timerCounter;
}
}, 1000);
this.backgroundMode.on('activate').subscribe(() => {
setInterval(function () {
this.startTimerCounter();
}, 240000);
})
}
}
【问题讨论】:
标签: javascript android cordova timer ionic4