Using setTimeout within a for loop to dispatch notifications

I'm facing an issue with sending notifications based on certain parameters. I attempted to use a combination of for loop and setTimeout in my code, but all the notifications are sent simultaneously instead of at timed intervals. The relevant snippet looks like this:

'this.times' is an array with multiple dimensions, while 'this.timer' is a variable determined by 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)
  }

Unfortunately, running this code triggers all notifications at once and I'm struggling to figure out a better approach.

Answer №1

Greetings and welcome to Stack Overflow! The reason for this behavior is due to the setTimeout function being non-blocking, causing it to return immediately. As a result, the loop rapidly sets all the timers, leading them to trigger almost simultaneously, making it difficult to discern any delay. To introduce a delay between notifications, you can modify your loop as follows:

const timer = ms => new Promise(resolve => setTimeout(resolve, ms))

async function sendAllNotifications() {
  for (let time of this.times) {
    this.localNotification()
    await timer(this.timer * 1000);
  }
}

sendAllNotifications();

As a result, your localNotification function will be updated as shown below:

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})
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the mat-radio button in one card to toggle all other cards as well?

Within my home.component.html file, you will find the following code: <div class="grid grid-cols-5 gap-4 pt-10"> <div *ngFor="let card of cards" class=""> <div *ngIf="card==null;then nil else notnil&q ...

Are there any Android applications specifically designed for editing Typescript files?

While this may not be a typical programming inquiry, I have phrased it in a binary manner in hopes of meeting the criteria. I have been utilizing Quoda on my Android device and have encountered the need to edit .ts / Typescript files, which the app does n ...

Having trouble running an Angular project using ng serve command?

When I try to run my angular template using the "ng serve" command, it doesn't work. Here is the code from my angular-cli.json: https://i.sstatic.net/lQ5Ma.png ...

What steps do I need to take to run my Angular project locally using globally installed npm packages?

I'm interested in maintaining all my packages globally, similar to how node package itself operates. For instance, if I have a package named "Highcharts" listed in my package.json file, I prefer to install it globally instead of creating a local node_ ...

How do I repeatedly display an HTML element using a loop in Typescript?

As a newcomer to Typescript, I am attempting to create a function that generates multiple buttons based on the data stored in an array. Initially, I tried using a for loop like this: splitLabels(Array: any){ if (typeof Array != "undefined& ...

Dealing with numerous dynamically generated tables while incorporating sorting in Angular: a comprehensive guide

I am faced with a challenge involving multiple dynamically created Angular tables, each containing the same columns but different data. The issue at hand is sorting the columns in each table separately. At present, I have two tables set up. On clicking the ...

Discovering the current date in Angular 8 by utilizing the form builder

Is there a way to automatically fill a form created with FormBuilder with the system's date and time when it is created, instead of the default date format? this.creationDate = moment().format(DATE_TIME_FORMAT); I want to update the creationDate fie ...

What is the best way to retrieve props for computed properties using Vue with Typescript?

Seeking help on accessing props data for my computed property. Here is the code snippet: <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ props: { color: String, shape: String, ...

Tips for customizing the appearance of the tooltip in echart using Angular

Need help with echart tooltip formatting. If you'd like to take a look at the code, click here: https://stackblitz.com/edit/angular-ngx-echarts-ty4mlq?file=src/app/app.component.ts const xAxisData = []; const data1 = []; const data2 = []; const data ...

Encountering an Unexpected Response Code of 400 while performing WebSocket handshake with Angular 5 in .NET Core 2.1

After starting my .net core 2.1 Angular 5 template, I encountered an error in Chrome: WebSocket connection to 'wss://localhost:44356/sockjs-node/840/eaa2iary/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 The ...

Using Protractor: Verifying if an input field is in focus and ready for text input

Is there a way to determine if an input field has focus? I attempted the following approach: in my .po.ts getEditInputField(fieldName: string) { return $(`input[data-e2e=${fieldName}]`) } In my .spec.ts it("should focus the Abschlag input field", ...

Having difficulties establishing a connection with the websocket URL generated by Spark Java

I'm currently working on creating a websocket using the sparkjava framework. Here is the code snippet for setting up the websocket: public final class MainWS { static Map<Session, String> USER_SESSION_MAP = new ConcurrentHashMap<>(); stat ...

Converting an array of arrays into an object with an index signature: A step-by-step guide

I find myself facing a challenge where I have two types, B and A, along with an array called "a". My objective is to convert this array into type B. Type A = Array<[string, number, string]>; Type B = { [name: string]: { name: ...

Sorting Dates in Angular 4 Using an Array

I am struggling with sorting an array of Dates in Angular 4. My goal is to arrange my Customer array based on the value of releaseDate. This is what I currently have: Inside the customer.component.ts file : sort() { this.customers.sort((a: Customer, b ...

Eliminate the AM and PM options from the input time selection dropdown menu in HTML

https://i.sstatic.net/wKeQk.png Is it possible to eliminate the AM / PM option from the input time format dropdown? The form builder currently uses a 24-hour format that includes the AM / PM field. ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...

Creating pluggable components for JavaScript projects using Angular 2 and Typescript

Is it possible to develop pluggable components in Angular 2 using Typescript for a JavaScript project? While any JavaScript code is considered valid Typescript code, what happens when you have already completed your JavaScript(ES5) project and need to inco ...

What is the most efficient method for transforming files using a heroku deployed application?

I'm currently developing a Discord bot deployed on Heroku that has a function to convert video files to .mp4 format and then embed the file in a reply message. When running the function locally, everything works fine. However, when running it on the d ...

Showing collections of items in a Kendo Grid column

I am tasked with presenting data in a grid format where the entire array needs to be displayed in one column. To illustrate, let's consider a basic example using the following data structure: export class Person { public Name: string; public ...

Avoid installing @types typings in dependencies

Can I prevent global typings from being included in installed dependencies? I recently installed a local dependency, which led to the node_modules folder of that dependency being copied over. Within this node_modules folder are @types typings that clash w ...