2

I get a seemingly random number whenever I paste this code:

for (var i = 1; i <= 5; i++) {
    setTimeout(function(x) { return function() { console.log(x); }; }(i), 1000*i);
    // 1 2 3 4 5
}

into the console in chrome and firefox. 258 in the below picture. What is that number?

enter image description here

Cerlin
  • 6,622
  • 1
  • 20
  • 28
Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • 1
    It also seems to add 5 each time... :/ – Squirrl Mar 03 '17 at 06:57
  • 2
    That number would be the return value from the last `setTimeout()`. – nnnnnn Mar 03 '17 at 06:57
  • shouldn't that be 5? – Squirrl Mar 03 '17 at 06:57
  • 2
    No, as in the number that the `setTimeout()` function returns, which is an ID that you can use with `clearTimeout()`. It has nothing to do with your loop counter. When you run code directly in the console, it prints the result of the last line of code executed (in addition to any explicit `console.log()`s, but in this case those happen later because of the timeouts). – nnnnnn Mar 03 '17 at 06:58
  • ahhh ok i see, thank you. – Squirrl Mar 03 '17 at 06:59
  • 1
    P.S. It's adding 5 each time because you call `setTimeout()` five times each loop, and usually those returned IDs are just one more than the previous one. (One way or the other they need to be unique, so that you can cancel a specific timeout.) – nnnnnn Mar 03 '17 at 07:03
  • it also seems to continue to increment one every second... This is interesting. http://stackoverflow.com/questions/17280375/in-javascript-how-can-i-access-the-id-of-settimeout-setinterval-call-from-insid – Squirrl Mar 03 '17 at 07:03
  • i made with same code one [fiddle](https://fiddle.jshell.net/2pmh5e8b/) , and give me 1,2,3,4,5. Could be from other code? – Álvaro Touzón Mar 03 '17 at 06:59

0 Answers0