JavaScript doesn't have block level scoping of variables, so the value of i
in any deferred functions will be the last value of i
from the loop (in your case, 101). You can either use a named function or an immediately invoked function expression to create a closure that gives the value the correct scope.
<script type="text/javascript">
var j = 0;
for(var i = 0; i <= 100; i++){
(function(i) {
setTimeout(function(){
console.log(i);
},j*2);})(i);
j++;
}
</script>
Also bear in mind that the second argument passed to setTimeout
is the delay in milliseconds, so that's a very short delay (a tiny fraction of a second) between each call.