+ 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.

26th Sep 2022, 5:50 PM
Madrine Nansiimbi
Madrine Nansiimbi - avatar
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. }
26th Sep 2022, 8:16 PM
Jayakrishna 🇼🇳
+ 3
But i is less than 3, I thought loops get excuted according to the condition đŸ€”
27th Sep 2022, 4:27 AM
Madrine Nansiimbi
Madrine Nansiimbi - avatar
28th Sep 2022, 7:00 AM
Madrine Nansiimbi
Madrine Nansiimbi - avatar
+ 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.
27th Sep 2022, 9:48 AM
Jayakrishna 🇼🇳
0
Hope it helped... You're welcome..
28th Sep 2022, 9:05 AM
Jayakrishna 🇼🇳