0

I'm trying to figure out why this for loop does not render out 0,1,2,3 like its suppose to.

It renders 4, 4 , 4, 4.

How would i get this to print 0, 1, 2, 3 with the setTimeout still in place ?

for (var i = 0; i < 4; i++) {   
    setTimeout(function() {     
        console.log('The index of this number is: ' + i);   
    }, 3000); 
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
randal
  • 1,272
  • 3
  • 23
  • 48

1 Answers1

1

Create another and call it on each iteration

function a(i)
{
 setTimeout(function() {     
        console.log('The index of this number is: ' + i);   
    }, 3000); 
}

for (var i = 0; i < 4; i++) {   
   a(i);
}
ellipsis
  • 12,049
  • 2
  • 17
  • 33