-2

I am trying to make a loop that fire every 3 seconds and trying to do so using Promises. I can't put a return within the loop though like below so I don't know how to accomplish this.

for (let x = 0; x < 4; x++) {
     return new Promise(resolve => {
         setTimeout(() => {
             console.log("timeout")
             resolve()
         }, 3000)

     });
};

1 Answers1

0

To do it in a loop, you would need to use await.

async function runIt() {
var start = Date.now()
for (let x = 0; x < 4; x++) {
     await new Promise(resolve => {
         setTimeout(() => {
             console.log("timeout", x, Date.now() - start)
             resolve()
         }, 3000)

     });
};

}

runIt();

You would be better off with just doing a recursive call

function runIt(times, method, delay) {
  var count = 0;
  function next() {
    method();    
    count++;
    if (count < times) window.setTimeout(next, delay);
  }
  // next(); // If you want no delay for first iteration
  window.setTimeout(next, delay);

}


function sayIt() {
  console.log("hello");
}

runIt(4, sayIt, 3000);
epascarello
  • 185,306
  • 18
  • 175
  • 214