1

This creates a 2 second delay and runs the loop. I need to create a 2 second delay for every iteration, not just once.

var myArray = ['test1','test2','test3'];

function doSetTimeout(index) {
  setTimeout(function() { console.log(myArray[index]) }, 2000);
}

var index;
for (index = 0; index < myArray.length; ++index) {    
    doSetTimeout(index)
}

Expected result would be:

test1 
(2 second delay)
test2 
(2 second delay)
test3
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
zadubz
  • 1,281
  • 2
  • 21
  • 36

1 Answers1

1

Just multiply your delay by the index

var myArray = ['test1','test2','test3'];

function doSetTimeout(index) {
  setTimeout(function() { console.log(myArray[index]) }, index * 2000;
}

var index;
for (index = 0; index < myArray.length; ++index) {
    doSetTimeout(index)
}
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64