1

Let's say I have this code:

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    setTimeout(function() { 
        console.log(entry); 
    }, 1000);
});

This waits 1 second and then logs a, b, and c all at once. I want to wait 1 second, log a, wait another second, log b, wait a third second, log c.

How do I execute a for loop so that each loop takes a second, and the following loops don't start until that second is up?

Joshua Soileau
  • 2,933
  • 9
  • 40
  • 51

3 Answers3

2

You can use setInterval() and clearInterval() to accomplish you task.

Try,

 var xCnt = 0;
 var a = ["a", "b", "c"];

 var xInterval = setInterval(function () {
     console.log(a[xCnt]);
     xCnt += 1;
     if (xCnt == a.length) {
         clearInterval(xInterval);
     }
 }, 1000);

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

Try this:

var i = -1;
var int = setInterval(loop, 1000);

function loop(){
  if( i >=0 && i < a.length){
    console.log(a[i]);
    i++;
  }
  else{ clearInterval(int);}
}
Ringo
  • 3,795
  • 3
  • 22
  • 37
0

Try multiplying the setTimeout by the index argument in forEach, like this:

var a = ["a", "b", "c"];
a.forEach(function(entry, index) {
    setTimeout(function() { 
        console.log(entry); 
    }, 1000 * (index + 1));
});

Demo here: http://jsfiddle.net/tjnicolaides/A8rvX/

TJ Nicolaides
  • 965
  • 6
  • 11