How to write a non-blocking, delayed for loop in JavaScript without recursion?

Advertisements

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.

>Solution :

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

Leave a ReplyCancel reply