0

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

3
  • because your 4 setTimeOut are started at the same time Commented Dec 4, 2020 at 0:33
  • Sure because JavaScript is asynchronous. which means you call the foo function immediately 5 times. Or let's say, talk to JavaScript: Give me print out 0 in 2 secs, and 1 in 2 secs... So after 2 secs, you get the result one by one. Commented Dec 4, 2020 at 0:36
  • Suggested to read the JavaScript Info Tutorial has part Nested SetTimeout. Commented Dec 4, 2020 at 0:38

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Working! Whats the reason that it doesnt print after 1 seconds and 2 seconds and 3 seconds etc...? Do you have a good source to read?
@OzHarary OP if you found this answer is useful, please accept it by clicking the check mark which's at the left side of an answer. Which means it solved your problem.
@OzHarary in the original post you're queueing 5 executions of the setTimeout with a 1 second delay immediately, whereas this takes the loop count into account.
setTimeout( console.log, 1000 * i, i);
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.