0

Why does this code print this result

for (var i =0 ; i< 3 ; i++ ) SetTimeout(fonction() { console.log(i)} ,1000)

27th Jan 2019, 11:22 AM
Sara Hadj-Ali
Sara Hadj-Ali - avatar
5 odpowiedzi
+ 1
So what we have here is a loop that does 3 times setTimeout(function(){ console.log(i) },1000); Now let's take a closer look at it setTimeout(func,delay) does something a delay miliseconds later, so in the case setTimeout(function(){},1000) it will do the function 1000 ms or 1 second later console.log(i) will output the for loop variable. So add those things together and we get this 0 - 2 will be printed with a delay of 1 second
27th Jan 2019, 11:32 AM
Roel
Roel - avatar
0
It actually print 3 3 3
27th Jan 2019, 11:34 AM
Sara Hadj-Ali
Sara Hadj-Ali - avatar
0
Then this has happend : The for loop takes less than 1 second to complete so at the time it has to print it will print i's current value which is 3
27th Jan 2019, 11:37 AM
Roel
Roel - avatar
0
It would print the current value of the for loop which in this case is at 3 stoped ,it catches it and print it then , Oh i understand it thank you ^^
27th Jan 2019, 11:40 AM
Sara Hadj-Ali
Sara Hadj-Ali - avatar
0
You're welcome
27th Jan 2019, 11:41 AM
Roel
Roel - avatar