+ 1

Is someone tell me what happened 😕?

Question is :- What will be the output? for (var i = 0;i <=5;i ++){ setTimeout(function (){ console.log(i) }, i * 1000) } Answer is :- 666666 WHY PLEASE EXPLAIN

5th Oct 2020, 3:14 AM
💀Shubham💀
💀Shubham💀 - avatar
2 Antworten
+ 8
Try this code: for (var i=0;i<=5;i++) { /*Empty*/ } console.log(i) What's the output of above code and why? About your original question: setTimeout waits for the current calculations to finish and then calls the callback(after waiting x seconds, where x is the other argumen passed). When those functions run, the loop have finished already and they search for a variable called i. They do find it, and its value is the one that results at the end of the loop. If you ran the code I gave you at the beginning you will understand.
5th Oct 2020, 3:57 AM
Kevin ★
+ 1
Kevin ★ Thanks 😀
5th Oct 2020, 7:09 AM
💀Shubham💀
💀Shubham💀 - avatar