Saturday 2 February 2013

Nested Async Loops

When working on one more of my "fun useless projects" involving repeating a set of animations (hope I'll post about it when I have time to complete it) I found myself writing a "Nested Async Loop", that is, an async function running inside 2 nested loops. The idea is simple and beautiful, as with normal async loops, the async function has to use its callback function to invoke the next iteration of the loop, the only addtions here is that when the loop is complete, it has to invoke the next iteration of the outer loop, so that it continues with the whole thing. This means we have 2 functions, one for each loop, that keep calling each other.

This example will try to make it clearer:

var outerLoop = (function(n){
 var i = 0; 
 return function(){
  if (i < n){
   console.log("- start i: " + i);
   innerLoop(i);
   i++;
  }
 };
}(5));

var innerLoop = (function(m){
 var j = 0; 
 return function(i){
  if (j < m){
   console.log("start i-j: " + i + j);
   setTimeout(function(){
    console.log("end i-j: " + i + j);
    j++;    
    innerLoop(i);
   }, 200);
  }
  else{
   j = 0;   
   outerLoop();
  }
 };
}(3));

outerLoop();

the above code is the async equivalent of these much more familiar lines :-)

for (var i=0;i<5; i++){
 for (var j=0;j<=3; j++){
  console.log("start i-j: " + i + j);
  console.log("end i-j: " + i + j);
 }
}

This nested async loop case prompted me to add a repeat method to my asyncLoop.js project. You can read more here.

No comments:

Post a Comment