Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

settimeout - JavaScript : For loop with timeout

I want that my for loop should not be executed at once, but wait for timeout after each iteration. For eg :

for(var i=0; i<10; i++) {
    console.log(i);
    //wait for 1000
}

I found many solutions on stack-overflow like this one :

for (var i=0;i<=10;i++) {
   (function(ind) {
       setTimeout(function(){console.log(ind);}, 3000);
   })(i);
}

But in all the implementations, the loop waits for 3000 milli-seconds initially and then executes the whole for loop at once. Is there a way that each iteration is called after waiting for 1000 milli-seconds.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can work that out with simple math :

for (var i=0;i<=10;i++) {
   (function(ind) {
       setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind));
   })(i);
}

1000ms : 0
4000ms : 1
7000ms : 2
10000ms : 3
13000ms : 4
...


Following the comments

It seem that your request is a bit blurry. if you want to do something after the last timeout, you can set a limit and compare the current index :

var limit = 10
for (var i=0;i<=limit;i++) {
   (function(ind) {
       setTimeout(function(){
           console.log(ind);
           if(ind === limit){
               console.log('It was the last one');
           }
       }, 1000 + (3000 * ind));
   })(i);
}

Fiddle : http://jsfiddle.net/Tn4A7/


I think I know what you want...

and it is to simply do

for (var i=0;i<=10;i++) {
   (function(ind) {
       setTimeout(function(){console.log(ind);}, 1000 * ind);
   })(i);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...