Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading