Array Plus Delay

by Kyle Mitofsky

HTML

<div style='position:fixed;bottom:0;left:0; background:lightgray;width:100%;'>
    About this SO question:
    <a href='https://stackoverflow.com/a/17246304/1366033'>
        setTimeout and array each
    </a>
</div>

JavaScript

function ArrayPlusDelay1(array, delegate, delay) {

  // initialize all calls right away
  array.forEach(function (el, i) {
    setTimeout(function() {
        // each loop, call passed in function
        delegate( array[i]);

      // stagger the timeout for each loop by the index
      }, i * delay);
  })
}

function ArrayPlusDelay2(array, delegate, delay) {
  var i = 0
  
  function loop() {
  	  // each loop, call passed in function
      delegate(array[i]);
      
      // increment, and if we're still here, recurse again
      if (i++ < array.length - 1)
          setTimeout(loop, delay);
  }
  // seed first call
  setTimeout(loop, delay);
}

function ArrayPlusDelay3(array, delegate, delay) {
  var i = 0
  
   // seed first call and store interval (to clear later)
  var interval = setInterval(function() {
    	// each loop, call passed in function
      delegate(array[i]);
      
        // increment, and if we're past array, clear interval
      if (i++ >= array.length - 1)
          clearInterval(interval);
  }, delay)
 
 return interval
}



//ArrayPlusDelay1(['a','b','c'], function(obj) {console.log(obj)},1000)
//ArrayPlusDelay2(['d','e','f'], function(obj) {console.log(obj)},1000)
var int = ArrayPlusDelay3(['x','y','z'], function(obj) {console.log(obj)},1000)

// clear with clearInterval(int)