Timing the loop iteration before passing the value to the function included

I'm currently exploring how to implement a timeout for a function within a loop iteration in an Ionic application using TypeScript.

setInterval will execute the function at equal time intervals in a continuous loop:

   setInterval(() => {
      this.myFunc1(val);
   }, 800);

setTimeout can achieve the desired outcome when executed sequentially:

   setTimeout(() => {
      this.myFunc1(val);
   }, 800); 

   setTimeout(() => {
      this.myFunc1(val);
   }, 1200); 

But the challenge lies in creating a loop with time intervals through an updated list, ensuring that each iteration waits for the previous iteration to finish before passing the second value val to the function or calling myFunc1:

 async myFunc2() {
    for (let val of this.myValueList) {
        /// Wait for 5 seconds or until the process is complete, then pass the value by calling the function:
        this.myFunc1(val);          
    }
}

Answer №1

setInterval is the best choice in this scenario. What's important to note is that you must remember to clear the interval as well. setInterval will give you an id which can be used with clearInterval to halt the looping.

In the following code, I am sending data to console.log, pausing for a second, and then repeating until completion.

const myValueList = [5,6,7,8,9,10];

let i = 0;
const id = setInterval(() => {
  console.log(myValueList[i++]);
  if (i === myValueList.length) {
    clearInterval(id);
    console.log("done!");
  }
}, 1000);

Answer №2

Here's an easy solution to wait for approximately 5 seconds:

const delay = time => new Promise(resolve => setTimeout(resolve, time));

Then, you can simply use this in your code like so:

async myFunction2() {
    for (let value of this.valueList) {
        await delay(5000);
        this.myFunction1(value);
    }
}

If myFunction1 is asynchronous and you want to wait for it to finish before continuing the loop, you can do:

async myFunction2() {
    for (let value of this.valueList) {
        await this.myFunction1(value);
    }
}

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

Express is throwing an error indicating that the specified route cannot be found. Is there a way to dynamically

After dynamically adding routes and sending a post request through Postman, I encountered a "not found" error message. In the app, a 404 is logged next to the endpoint, indicating that Express cannot locate it. However, I know that I added the router dynam ...

Building a user interface with React JS to iterate over an array using the map function, passing each item as a parameter

I have been instructed to create an interface for my code related to .map, but I am unsure about how to proceed. I have been searching for examples without any luck so far. I have isolated the specific code with ###. Any assistance in this matter would be ...

Locate items that possess identical property values and append them to a new array as a property

I am dealing with an array containing objects that have a specific property called "operationGroup" with the sub-property "groupId". Here is an example of the array structure: [{ operation: 11111, operationGroup: null }, { operation: 22222, ...

What is the location of the Typescript project path in Visual Studio 2015 Cordova?

In my development journey, I decided to create a Typescript blank Cordova project within Visual Studio 2015. After adding a small test bit of ts code... function onResume() { // TODO: This application has been reactivated. Restore application st ...

Why is my "webpack" version "^5.70.0" having trouble processing jpg files?

Having trouble loading a jpg file on the Homepage of my app: import cad from './CAD/untitled.106.jpg' Encountering this error message repeatedly: assets by status 2 MiB [cached] 1 asset cached modules 2.41 MiB (javascript) 937 bytes (rjavascript ...

Speedily deliver a message to the designated destination

I have a specific route set up at /test: app.route('/test', (req,res)=>{ res.sendFile(__dirname + "\\myhtml.html") }) Now, I want to trigger an event in Node.js on the /test route, and have myhtml.html file listen for ...

Navigate to the middle of the visible area

Is there a way to automatically center a div when it is clicked, so that it scrolls to the middle of the browser viewport? I have seen examples using anchor points but I want to find a different solution. Any ideas on how to accomplish this without using ...

PHP is receiving data from $.post in an invalid format

I am facing a challenge in sending a JavaScript Object() to a PHP file in the correct format that $.POST requires. The PHP file does not establish any $_POST[] variables, which suggests that I may be transmitting the data in an improper format. JS: $(&ap ...

Removing a specific date value within an object contained in an array, then organizing the array in descending order based on the latest date

I need help sorting an array of objects by the most recent created_at value while maintaining the entire object in that order. Currently, my code only returns the create_at value instead. How can I adjust the map function to avoid separating the created_a ...

Retrieve elements from an array based on the value of an object

I have a list of items that resembles the following structure: var entries = [ { sys: {id:"1"}, fields: "article1" }, { sys: {id:"2"}, fields: "place1" }, { sys: {id:"3"}, fields: "offer2" }, { sys: {id:"1"}, fields: "article2" }, { sys: {id:"1" ...

Combining React, Typescript, and asynchronous Promises

Currently I am in the process of developing a component that interacts with a webservice to fetch data asynchronously using promises. Once the promise is fulfilled, I intend to integrate the results into my component's rendering method. My ultimate go ...

Picked (chosen-js): Steps to deselect options using a variety of selectors

I am currently using the Chosen library on Vue and Webpack for my project. I have a scenario where I need to cancel a selection when multiple options are selected, but I am struggling to achieve this. Can anyone guide me on how to cancel a selected optio ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...

In JavaScript ES6, the const keyword can unexpectedly be altered even though it is intended to be constant

While experimenting with ES6, I came across an interesting feature - const values cannot be changed or reassigned. However, I noticed that in certain scenarios, it seems like we can change them. Can someone explain this? { const name = 'unchangabl ...

Sending parameters with $location.path() in AngularJS

Having trouble creating a redirection call in the controller with a numerical parameter. Here is the code I've been using: $location.path('/tasklist/:$rootScope.job_id'); I have also attempted the following: $location.path("/tasklist/",$r ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

What is the best way to incorporate a table name into a MySQL query using ExpressJs?

My goal is to retrieve the contents of a specific table using this code snippet: let tableName = req.body.login connection.query('SELECT * FROM ?', tableName, (err, rows) => { if (err) throw err res.send(rows) }) However, as tableName ...

What steps do I need to take to ensure that Phaser implements modifications made in my game.js file?

I recently completed the Phaser Tutorial and set up my project with an index.html file and a game.js file, along with downloading the phaser.min.js file. All files are located in the same folder. Although I have connected everything correctly and the outp ...

Angular issue: "Unable to bind to 'ngModel' as it is not recognized as a property of 'input'"

While working with Angular 4, an error message appears in the console: The 'ngModel' property cannot be bound since it is not recognized as a valid property of the 'input' element Is there a solution to fix this issue? ...

Dealing with models in Vue.js is proving to be quite a challenge

Why isn't myGame showing as 超級馬力歐 initially and changing when the button is pressed? It just displays {{myGame}} instead. I'm not sure how to fix it, thank you! let myApp = new vue({ el:'myApp', data:{ myGame:&a ...