0

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.

Mubashir Kp
  • 255
  • 1
  • 2
  • 7
  • 3
    You can use a callback function – forgottofly Aug 05 '15 at 05:46
  • could you elaborate..? – Mubashir Kp Aug 05 '15 at 05:48
  • Pls check this link http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ – forgottofly Aug 05 '15 at 05:49
  • 1
    http://stackoverflow.com/questions/8027392/making-a-function-to-wait-an-event-before-returning Does this help you? I suggest you to write your logic behind posting only single for-loop here. Some expert of stackoverflow may have better way to solve this problem instated of waiting. – MrYo Aug 05 '15 at 05:51

2 Answers2

2
     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
Alex Nikulin
  • 8,194
  • 4
  • 35
  • 37
1

use recurcive function;

demo($firstFrame,1)

function demo(firstFrame,i){
    if(i<6){
       //do something
       i++;
       setTimeout(function(){
          demo(firstFrame,i);
       },1000)
    }
}
user3227295
  • 2,168
  • 1
  • 11
  • 17