Frage

I´m having trouble to delay a function in a for-loop. So here is my test:

<script type="text/javascript">
var j = 0;
for(var i = 0; i <= 100; i++){
    setTimeout(function(){
        console.log(i); 
    },j*2);
    j++;
}
</script>

I want that every count will appear step by step with a delay in the console. But currently only 101 appears 101 times. Why and what is a better solution?

Cheers

War es hilfreich?

Lösung

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.

Andere Tipps

function SetTimeoutLoop(i) {
  setTimeout(function() { console.log(i); }, i*2);
}

for(var i = 0; i <= 100; i++){
    SetTimeoutLoop(i)
}

JSFIDDLE

u may try this:

<script type="text/javascript">
var j = 0;
for(var i = 0; i <= 100; i++){
  (function(i, j){
    setTimeout(function(){
        console.log(i); 
    },j*2);
  })(i, j);
  j++;
}
</script>

It happens as once your callback starts to fire your loop would be finished and the value will be max.

you can do like

(function me(i,j) {

    if(i <= 10) {

        setTimeout(function(){

            alert(i++);
            me(i,j);

        },j++*2);
    }

})(0,0);

Here is a sample fiddle.

You can't do that in for loop, instead you should use a recursive function like this:

here's a fiddle

var j = 0;
var i=0;


setTimeout(function(){
    log_i(i);
},j*2);

function log_i(i){
    console.log(i);
    i++; 
    if(i<=100){
       setTimeout(function(){  log_i(i); },j*2);   
    }
    j++;
 }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top