JavaScript : For loop with timeout

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);
}

Leave a Comment