0
Why does this code print this result
for (var i =0 ; i< 3 ; i++ ) SetTimeout(fonction() { console.log(i)} ,1000)
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
0
It actually print
3
3
3
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
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 ^^
0
You're welcome