2

I'm new to asynchronous programming, and I'm having a hard time getting the concept. Please help!!!

Ive come up with a simple example:

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

All I want is to print the indexes in ascending order but due to asynchronous action forced by the setTimeout i'm getting the last index printed out 10 times.

I understand why this happens...

No matter what I've tried (I don't think my misunderstanding needs elaboration) I failed solving this stupid riddle...

Im obviously missing something basic. Please help me figure it out.

  • 3
    I think it's the concept of closures that's confusing you, not asynchronous calls. What you're doing there is setting 10 timeouts, each of which will wait for a second before firing. When they do fire, they will each refer back to 'i', which now equals 10. – Alan Oct 25 '14 at 20:13
  • Array.apply(null, Array(10)).map(function(a,b){ setTimeout(console.log.bind(console,b), b * 1000);}) – dandavis Oct 25 '14 at 21:10

1 Answers1

2

It's because all those functions use the same variable i, which is equal to 10 during invocation of them. Try something like this:

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

It's because JavaScript has closures. You can read about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

Kuba Jagoda
  • 4,908
  • 2
  • 19
  • 21