title: SetTimeout inside a for loop
body: <p>I'm trying to write a script that changes the z-index of 3 images. Basically the script should target the current image and apply a higher z-index on the next image, like a sort of carousel but with a z-index rather then active class. The challenge is to set the z-index after a specific interval. The problem is that the first image is displayed and then the last one. This is my code:</p>
  
  <p>Html:</p>
  
  <pre><code>&lt;div class="changingimages"&gt;
      &lt;img src="#" data-time="3000" width="100%" class="alternateimage alternateimage1"&gt;
      &lt;img src="#" data-time="2000" width="100%" class="alternateimage alternateimage2"&gt;
      &lt;img src="#" data-time="4000" width="100%" class="alternateimage alternateimage3"&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>jQuery Script</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  
  jQuery(document).ready(function(){
  
      var changeImg = function(i, time, currentImg) {
  
          setTimeout(function(){
  
              jQuery(currentImg).next().css("z-index", i);
  
          }, time);
      };
  
      var numberOfChilds = jQuery(".changingimages").children().length;
      var currentIndexClass;
      var currentImg;
      var time;
  
      for (var i=1; i&lt;=numberOfChilds; i++) {
  
              currentIndexClass = '.alternateimage' + i;
              currentImg = jQuery(currentIndexClass);
              time = jQuery(currentIndexClass).attr("data-time");
  
              changeImg(i, time, currentImg);
  
      }
  
  });
  </code></pre>
  
  <p></p>
  
  <p>I think there is some problem with the closure inside a loop, but not sure!</p>