2

Why is this function only sending the number 10 ten times. I want it to send 1... 2 ... 3 ... 4 ... 5 and so on but instead its showing 10....10.... 10... 10... I'm not sure why it would. How do I make a loop that returns distinct values?

  for (i = 0; i < locations.length; i++) {

  setTimeout(function() { alert("test"+i.toString()) ; }, 100);
                                                                              }

How do I make a loop that returns distinct values?

Peter S McIntyre
  • 409
  • 4
  • 12

1 Answers1

3

You can do this by using a closure (pass i back into an immediately invoked function expression (IIFE)). This will maintain the value of i:

for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(function() {
      console.log("test" + i);
    }, 100);
  })(i);
}

To increment the timeout by using the i works the same way. Making sure to wrap the entire timeout call with the IIFE:

for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(function() {
      console.log("test" + i);
    }, i * 100);
  })(i);
}
KevBot
  • 17,900
  • 5
  • 50
  • 68