Mubashir Kp
Mubashir Kp

Reputation: 265

how to make for loop wait for a function to execute in javascript

I have a for loop which invokes a function with loop variable as the paramter. i need the for loop to wait until the first invocation is executed, before the next

for(i=1;i<6;i++){
 demo($firstFrame,i)
}

how do we make the for loop wait.

The demo function has a timeout in it there for obviously the for loop will have to wait before invoking the function for the second time.

Upvotes: 0

Views: 738

Answers (2)

Alex Nikulin
Alex Nikulin

Reputation: 8679

     var demo = function(name, index, onCompleteFunc){
         /**do staff**/
         onCompleteFunc();// exec this func when you are done.
     }; 

     var iterator = function(iteration){
         if(iteration >= 0){
             demo($firstFrame, iteration, function(){
                        iterator(iteration-1);
             });
         }  
     }

     iterator(5);//this function start recurcively execute demo with indexes from 5 to 0

Upvotes: 2

user3227295
user3227295

Reputation: 2156

use recurcive function;

demo($firstFrame,1)

function demo(firstFrame,i){
    if(i<6){
       //do something
       i++;
       setTimeout(function(){
          demo(firstFrame,i);
       },1000)
    }
}

Upvotes: 1

Related Questions