I ain't understanding the behavior here

This snippet was supposed to give the 1 2 3 as a result but it is printing 3 time 3 why?
Suggest me a good article on this

for(var i = 0; i < 3; i++){
    setTimeout(function func() {
        console.log(i);
    }, 1000);
}

With setTimeout you are delaying the console.log(i) until after the loop body has executed 3 times and i = 3. Then the three console.log(i) commands are executed and you see three 3s logged.

then it should print second 3 after 1 second of first 3 and so on but it prints all at a time why?

I’m not sure that I understand your question. I am seeing the console pause for 1 second and then execute the three function calls. At this point, i=3, so 3 is printed 3 times.

The three different commands that are being delayed are miliseconds apart, so they all execute miliseconds apart after the 1 second delay.

thank you so much still I have a confusion that setTimeout method is getting called 3 times or one time? shouldn’t it get called three times as loop iterate three times and if setTimeout gets called three times then it should take 1 second for every execution. I am thinking in this way but I might be wrong as I am a beginner :neutral_face:

The function setTimeout is being called three times, but the function does not halt the execution of the loop. The loop still executes three times nearly instantly.

They are all queued up using the same delay. There isn’t a one-second delay between each call. It is like if you had 3 calls to 3 setTimeouts and ran them all in the console at the same time.

setTimeout(function func() {
    console.log('test');
}, 1000);
setTimeout(function func() {
    console.log('test');
}, 1000);
setTimeout(function func() {
    console.log('test');
}, 1000);

// test
// test
// test

Here it is with a different delay for each call.

for(let i = 0; i < 3; i++){
    setTimeout(function func() {
        console.log(i);
    }, 1000 * i);
}

Also, just to be clear, the delay does not block code execution and that is not the point of asynchronous code.


1 Like

I think article on closures could help:

1 Like

The loop is executing three times nearly instantly understood this part but as setTimout is being called three times so shouldn’t it print 3 within 3 seconds because every invocation of setTimeout should take 1 second

No it is not the invocation of setTimeOut that is delayed, it is the invocation of console.log and they all have the same delay.

1 Like

thank so much now i got the point , this is all I was trying to understand and you make it so simple thanks again :slightly_smiling_face:

Try let instead of var to blow your mind … :stuck_out_tongue_winking_eye:

for(let i = 0; i < 3; i++){
    setTimeout(function func() {
        console.log(i);
    }, 1000);
}

if you want to go deeper …
read about “loop heads” in this doc
https://2ality.com/2015/02/es6-scoping.html