1

This question seems super-primitive but I can't figure it out.

I have a code like this. I would expect the result be three alerts "0", "1" and "2". However, that's not what happens - I get three 2s.

for(var i=0; i<3; i++) {

   var j=i;
   setTimeout(function() {

      alert(j);

   },1000);
}

The code is at http://jsfiddle.net/8UMCA/.

How to "fix" the code so it alerts "0"-"1"-"2"?

Karel Bílek
  • 36,467
  • 31
  • 94
  • 149
  • 1
    You need to create a closure: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – rgthree Mar 05 '14 at 22:55

2 Answers2

1

This got it working.

for(var i=0; i<3; i++) {
   setTimeout(function(j) {

      alert(j);

   }(i),1000);
}
Karel Bílek
  • 36,467
  • 31
  • 94
  • 149
1

Or this

for(var i=0; i<3; i++) {          

       (function(){
             var j=i;
            setTimeout(function() {

            alert(j);

        },1000);           
       }
       )();



   }
Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59