skip to Main Content

I want a for-loop that executes its code every X amount of milliseconds. It should be non-recursive to avoid a stack overflow after many iterations. Also, it should be non-blocking, and its performance should be decent.

I tried it with a promise:

(async () => {
  for (var i = 0; i <= 30; i++) {
    await new Promise(async (res, rej) => {
      setTimeout(() => {
        console.log("run number", i);
        res();
      }, 100);
    });
  }
})();

But the first execution is after the duration passed to setTimeout, not once before like in a real for-loop.

2

Answers


  1. Chosen as BEST ANSWER

    I think I got it. Here my solution:

    (async() => {
      for (let i = 0; i <= 30; i++) {
        console.log("run number", i);
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
    })();


  2. You’ll have to pull the function that does whatever work you want to do out of the loop. Then you can call it before the loop starts for the first iteration, and then after the timed intervals thereafter.

    (async () => {
      function doWork(iteration, finish) {
        console.log(`run number ${iteration}`);
        finish();
      }
    
      doWork(0, _ => _);
      for (var i = 1; i <= 30; i++) {
        await new Promise(async (res, rej) => {
          setTimeout(() => {
            doWork(i, res);
          }, 100);
        });
      }
    })();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search