0

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.

Xhuliano
  • 3
  • 1
  • 2
  • 4
    Does this answer your question? [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Osama Bin Saleem Jun 29 '21 at 08:42

1 Answers1

0

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})
  }
Osama Bin Saleem
  • 779
  • 1
  • 12
  • 24