Why the second (i) in the loop/in the timer wasn't immediately 6? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why the second (i) in the loop/in the timer wasn't immediately 6?

https://code.sololearn.com/W5LzbrgVsFrw/?ref=app

6th May 2021, 1:25 AM
Ayoob Saad
Ayoob Saad - avatar
5 Answers
+ 2
You need to know how setTimeout works and how the value of i comes from the function's context to understand why only 6 is printed by the following code: for(var i = 1; i<= 5; i++){ setTimeout(function(){ console.log(i) }, i*1000) //why this (i) wasn't 6 immediately } When i = 1, this runs: setTimeout(function(){ console.log(i) }, 1000) // The i * 1000 expression evaluates immediately to 1000 but the function isn't run right away. When i = 2, this runs again: setTimeout(function(){ console.log(i) }, i * 1000) // The i * 1000 expression evaluates immediately to 2000 but the function still isn't run. i then goes through 3, 4, 5 in a similar way. The for-loop exits after i becomes 6 and fails the loop condition. This will be less than 1 millisecond after the loop began at i = 1 because the loop finishes as fast as possible and computers are very fast. Almost 1 second later, it runs function(){ console.log(i) } At this point, i = 6 so 6 is printed.
6th May 2021, 7:36 AM
Josh Greig
Josh Greig - avatar
+ 1
If you just want to console.log the values without delay, use 0 as your setTimeout interval instead of i*1000. Even with an interval of 0, your function won't be called until the loop finishes. setTimeout always queues up the calls for later. With an interval of 0, it'll just be as soon as possible after your loop finishes.
6th May 2021, 7:42 AM
Josh Greig
Josh Greig - avatar
+ 1
All 5 times it prints, i is 6. This is because it never changes values in your anonymous function. The for-loop is the only code that changes the value of i and that runs before any of your anonymous functions. If you run this code, it'll print 6, 7, 8, 9, 10 because the timeout function is changing the value of i: for(var i = 1; i<= 5; i++){ setTimeout(function(){ console.log(i) i++; }, i*1000) //why this (i) wasn't 6 immediately }
6th May 2021, 5:35 PM
Josh Greig
Josh Greig - avatar
0
Josh Greig thank you so much i really appreciate ur effort, but i was asking about the second (i), it had to be (6) not (12345)
6th May 2021, 7:44 AM
Ayoob Saad
Ayoob Saad - avatar
0
I guess it went through the process of incrementing (i) because it was implemented inside the loop, unlike the the setTimeout which was invoked later outside the loop.
6th May 2021, 7:45 AM
Ayoob Saad
Ayoob Saad - avatar