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
I think I got it. Here my 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.