Issue
I'm trying to send a notification based on some parameters and I tried to use a for loop and setTimeout but when i run it all notifications are sent at once. The code looks like this:
this.times is an array of n dimension. this.timer is a variable based on user input
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)
}
when i try to run it all notifications are sent at once and i'm having truble understending how to do it differently.
Solution
Welcome to SO! This is because the setTimeout function is non-blocking and will return immediately hence the loop will set all the timers very quickly and all of them will trigger almost at the same time so you don't see the difference. If you want to send notifications with some delay you can add some delay in your loop like this:
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();
and you localNotification function will become:
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})
}
Answered By - Osama Bin Saleem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.