Reputation: 15
If I use setTimeout in a loop so only after the loop ends it executes all the operation in the same time. I tried to put setTimeout in a separate function, as suggested by many articles, but it does not help. The code is very simple:
function foo(i)
{
setTimeout( function() {console.log(i);}, 2000);
}
for (let i=0; i<5; i++)
{
foo(i);
}
It prints 0 1 2 3 4 in one shot
Upvotes: 0
Views: 77
Reputation: 5294
you could also do it with a generator. a generator can pause midway through a function https://www.javascripttutorial.net/es6/javascript-generators/
function* generator() {
let index = 1;
while (index <= 5) {
yield index++;
}
}
let f = generator();
var interval = window.setInterval(function(){
const obj = f.next();
if (obj.done){
clearInterval(interval);
} else {
console.log(obj.value)
}
}, 1000);
Upvotes: 1
Reputation: 181
It's because the proccess registry the 5 setTimeout at almost the same time.
Try with the different timeout time like this:
function foo(i)
{
setTimeout( function() {console.log(i);}, 1000 * i);
}
for (let i=0; i<5; i++)
{
foo(i);
}
Upvotes: 1