0

I tried running this snippet of code for which I tried consoling the i value inside setTimeOut() function and the o/p i got is 5 for 5 times with a time interval of 3 seconds each, can anyone please explain this snippet?

for (var i = 0; i < 5; i++) {
  console.log(i);
  setTimeout(function() {
      /////Why is this console.log printing 5?
      console.log(i);
    },

    i * 3000);
  console.log("i:", i)
}

OutPut:

0
i: 0
1
i: 1
2
i: 2
3
i: 3
4
i: 4
5
5
5
5
5
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Ammie
  • 3
  • 2

3 Answers3

0

Let's assume this code

console.log("a"),
setTimeout(function() {
  console.log("b");
},3000);
console.log("C")

The output of the code will be a, C, b Due to setTimeout is a call back function. And callback function executes after executing every line of code present in a function. Make your code accordingly with this theory it might help you to clear your concepts. Thanks

0

The callback passed to setTimeout is added to the event queue after the interval. As the interval increases in each iteration by 3 seconds(i * 3000) the 5s are logged with an interval of 3 seconds.

More about event queue.

All of the logs inside the callback are 5 because of the function scoped variable declaration var i=0. When the loop completes and callbacks in the queue are executed, the variable i will have the value 5 (as the condition i<5 fails when i is 5).

Scope of variables.

Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32
0

Because the value of variable "i" increased by one after the loop close. Your loop run with i=4 then after reaching the end of the for loop block it gets increase by 1 and became 5, after increasing the condition get checked 5<5 and the loop exit. The javascript compiler store variables declared with var keyword on it's global storage so the end of the loop won't free the memory it reserve. You can change this behavior by declare variable I with let keyword instead.

Ayman Ali
  • 567
  • 4
  • 11