-2

Why my for loop doesn't log different values of i on different line instead of it log 5 times 6.

Here is the code snippet.

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

**

Shekh Ataul
  • 43
  • 1
  • 5

1 Answers1

1

You can try this it will work

for (var i = 1; i <= 5; i++) {
        (function(ind) {
        setTimeout(function(){console.log(ind);}, 1000 + (1000 * ind));
        })(i)
}
jignesh patel
  • 964
  • 7
  • 13
  • Thanks jignesh patel. But can u explain me why my code is printing 5 times 6? – Shekh Ataul Jul 14 '17 at 13:58
  • just setting a timeout for loop execution not stops. and when time out completed value of i is 6 as loop execution completed. – jignesh patel Jul 14 '17 at 14:01
  • well, First of all i m beginner. U mean if i lowerthe timeout seconds then i will get different value? But i tried, the output is still same. – Shekh Ataul Jul 14 '17 at 14:16
  • Is the loop firsth executed whole and i gets incremented to the 6, then afterwards timeout method start to executed? – Shekh Ataul Jul 14 '17 at 14:18