title: Javascript async loop inside another async loop
body: <p>I have some code in jQuery that iterate through children in div using each().
  Every text inside is splitted into words. Each word is processed with 'for' loop.
  This function can take a long time and can freeze the browser so...</p>
  
  <p>Is there a way to create asynchronous loop inside another asynchronous loop but one is waiting for other to finish?</p>
  
  <p>Could anyone tell me the right direction?</p>
  
  <p>I came up with something like this:</p>
  
  <pre><code>var queue = [];
  var nlevel = 0;
  
  function work() {
      nlevel = queue.length-1;
  
      var arr = queue[nlevel][0];
      var process = queue[nlevel][1];
      var cnt = queue[nlevel][2];
      var item = arr[cnt];
  
      process.apply(item);
  
      cnt++;
      queue[nlevel][2] = cnt;
  
      if (cnt &lt; arr.length) {
          setTimeout(work, 1);
      } else {
          if (queue.length&gt;1) {
              queue.pop();
              setTimeout(work, 1);
          }
      }
  }
  
  function each(arr, process) {
      queue.push([arr, process, 0]);
  
      setTimeout(work, 1);
  }
  
  
  each(['one', 'two', 'three'], function() {
      alert(this);
  
      each([1, 2, 3, 4], function() {
          alert(this);
      });
  });
  </code></pre>
  
  <p>but It has some major bug and I couldn't fix it.</p>