setTimeout内部用于循环发送通知



我试图根据一些参数发送通知,并尝试使用for循环和setTimeout,但当我运行它时,所有通知都会同时发送。代码如下:

this.times是一个n维的数组。this.timer是一个基于用户输入的变量

for(let i of this.times) {
this.localNotification()
}
localNotification() {
setTimeout(() => {
this.date = new Date()
this.localNotifications.schedule({
text: "Hey it's time to take a picture",
trigger: {at: new Date(new Date().getTime())},
led: 'FF0000',
sound: 'file:/storage/emulated/0/media/audio/notifications/CwtChime.ogg'
})
this.notificationList.unshift({Title: "Time to take a picture", Body: "Hey, it's been a week since you took a picture, please take one", Reminder: true, Time: `${this.date.toLocaleString()}`, Seen: false})
}, this.timer*1000)
}

当我尝试运行它时,所有的通知都会同时发送,我已经了解了如何以不同的方式进行操作。

欢迎来到SO!这是因为setTimeout函数是非阻塞的,并且会立即返回,因此循环会非常快地设置所有计时器,并且所有计时器几乎同时触发,所以你看不到区别。如果你想发送延迟通知,你可以在循环中添加一些延迟,如下所示:

const timer = ms => new Promise(res => setTimeout(res, ms))
async function sendAllNotifications () { // We need to wrap the loop into an async function for this to work
for (let i of this.times) {
this.localNotification()
await timer(this.timer*1000); // then the created Promise can be awaited
}
}
sendAllNotifications();

您的本地通知功能将变为:

localNotification() {      
this.date = new Date()
this.localNotifications.schedule({
text: "Hey it's time to take a picture",
trigger: {at: new Date(new Date().getTime())},
led: 'FF0000',
sound: 'file:/storage/emulated/0/media/audio/notifications/CwtChime.ogg'
})
this.notificationList.unshift({Title: "Time to take a picture", Body: "Hey, it's been a week since you took a picture, please take one", Reminder: true, Time: `${this.date.toLocaleString()}`, Seen: false})
}

最新更新