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 --
  • 54,565
  • 8
  • 62
  • 98
randal
  • 1,192
  • 2
  • 19
  • 43

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
  • 11,688
  • 2
  • 14
  • 33