+ 3
How is this code possible to output 333?
for(var i = 0; i<3;i++){ setTimeout(function(){ document.write(i) },200) } Output of soloLearn challenge (333) But when I run it , output is( 012), please help.
5 Answers
+ 4
/*
recheck :
setTimeout triggers the function() after completing 200nano seconds. In between loop completes it's execution and came to result I=3, and it is 3 times called will be completed after it.
*/
for(var i = 0; i<3;i++){
setTimeout(function(){
document.write(i) //333
},200);
console.log(i); //012 see in js console.
}
+ 3
But i is less than 3, I thought loops get excuted according to the condition đ€
+ 3
Thanks Jayakrishnađźđł
+ 1
Yes. Madrine Nansiimbi
first when i=0 , the setTimeout sets the starting of Ananimous function
function() {
document.write(i);
}
after 200ns. Until it is like, pushed to stack. loop continue it's execution. So console.log(i) executed first before document.write(i).
This is repeated until i<3.
After 200ns, the function is popped from stack for execution. And then printed i value. And then i is 3.
You can notice that loop completed when 3<3.
To see, it clearly set timeout 2000*(i+1)
And print
document.write( ++i ) ;
**first function time out is 2000
** second time out is 4000
** 3rd time out is set to 6000
You can see clear execution i think.. they are independently set to print i..
As you expected loop stops at 3<3 but before it, function with having document.write(i) will set to start execute after 200ns completion.
0
Hope it helped... You're welcome..