+ 5

The code below loggeg '3 ,3 ,3' as output.How can I fixed it to log '0, 1, 2'?

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

15th Feb 2021, 8:22 AM
Apongpoh Gilbert
Apongpoh Gilbert - avatar
6 Réponses
+ 4
Change `var` to `let` for( let i = 0; i < 3; i++ ) // rest of code I don't know how to explain that though : ) I recall this question been asked before, but maybe the previous threads had irrelevant title or tag, I just can't find them using search terms I figured related.
15th Feb 2021, 8:36 AM
Ipang
15th Feb 2021, 8:41 AM
Abhay
Abhay - avatar
+ 2
Thanks Ipang but really need an explantion of the code
15th Feb 2021, 8:41 AM
Apongpoh Gilbert
Apongpoh Gilbert - avatar
+ 1
Thanks Abbay
15th Feb 2021, 8:50 AM
Apongpoh Gilbert
Apongpoh Gilbert - avatar
0
Apongpoh Gilbert Do you need that setTimeout is it importen for code?
23rd Feb 2021, 9:58 PM
Abdellah
Abdellah - avatar
0
The setTimeout() method calls a function or evaluate an expression after a specicified number of time. It is not imported
24th Feb 2021, 5:37 AM
Apongpoh Gilbert
Apongpoh Gilbert - avatar