title: Calling setTimeout function within a loop
body: <p>I'm new to javascript and am trying to call a function using setTimeout from within a <em>for</em> loop. The loop executes for each member of a nodeList.</p>
  
  <p>I'm finding that the function I'm calling with setTimeout is only actually executing during the last iteration of the loop. In the example below, I would like to make three separate calls to setTimeout but I'm finding that the first two calls are ignored.</p>
  
  <pre><code>function moveants(e, stepdistance) {
  
      . . . . .
  
      for(var i = 0; i &lt; 3; i++)
      {
          var nextAnt = antgroup.childNodes[i]
          nextAnt.count = 0;
          nextAnt.member = i;
          setTimeout(function () { takeStep(nextAnt, mouseclickX, mouseclickY, 10) }, 0);
      }
  }
  
  function takeStep(ant, destX, destY, stepDistance) {
  
      . . . .
  
      . . . .
  
      if( condition )
      {
          return;
      }
      else
      {
          takeStep(ant, destX, destY, stepDistance);
      }
  }
  </code></pre>
  
  <p>I have seen <a href="https://stackoverflow.com/questions/315078/how-do-you-handle-multiple-instances-of-settimeout">other posts</a> that describe making multiple calls to setTimeout. Amazingly (to me), the multiple calls will work if I simply take them out of the <em>for</em> loop like this.</p>
  
  <pre><code>    setTimeout(function () { takeStep(antgroup.childNodes[0], 
           mouseclickX, mouseclickY, 10) }, 10);
      setTimeout(function () { takeStep(antgroup.childNodes[1], 
           mouseclickX, mouseclickY, 10) }, 10);
      setTimeout(function () { takeStep(antgroup.childNodes[2], 
           mouseclickX, mouseclickY, 10) }, 10);
  </code></pre>
  
  <p>I just can't figure out why there is a difference between calling them from within a <em>for</em> loop and calling them outside of one. </p>
  
  <p>I am getting valid return values from the setInterval call in every case.. it's just that with only the last iteration of the <em>for</em> loop does the function actually execute.</p>
  
  <p>Thanks in advance for any help.</p>