Search code examples
javascripttypescriptfor-loopsettimeoutsetinterval

Loop iteration with time interval before passing value to included function


I'm trying to figure out how to set time out for function inside the loop iteration in Ionic TypeScript application.

setInterval makes equal time interval with calling the function in endless repetition:

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

setTimeout gives required result if listed sequentially:

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

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

but how to loop with time interval trough the updated list and wait while pass second value val to the function, or call myFunc1 when it will be finished in previous iteration:

 async myFunc2() {
    for (let val of this.myValueList) {
        /// wait for 5 sec or wait for finishing process, then pass value calling function:  
        this.myFunc1(val);          
    }
  }

Solution

  • setInterval is the correct choice here. What's missing is that you need to clear the interval. setInterval returns an id that you can pass to clearInterval which stops the iteration.

    Here I'm passing data to console.log, waiting a second, then repeating till done.

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