Javascript: How to loop through every array's item every second

Viewed 5867

Lets say i have an array like this:

var arr = [0,1,2,3,4];

so i want to make a for loop that loops through the array and console logs every item, but i want it to console log separately every item and each item will be console logged a second after the previous item, how can i do this?

4 Answers

You can use an interval. Here is an example:

var arr = [0,1,2,3,4];
var index = 0;
setInterval(function(){
    console.log(arr[index++ % arr.length]);
}, 1000)

The example above will loop through the array more then once. If you want to loop the array only once, you can stop the interval when all the elements were logged.

var arr = [0,1,2,3,4];
var index = 0;
var interval = setInterval(function(){
     console.log(arr[index++]);
     if(index == arr.length){
        clearInterval(interval);
     }
}, 1000)

Just thought I'd clean up @mhodges answer a little bit, with a cleaner ES6 generator function:

let myArray = [0, 1, 2, 3, 4]

let interval = setInterval(gen => {
  const { value, done } = gen.next()
  
  if (done) {
    clearInterval(interval)
  } else {
    console.log(value)
  }
}, 1000, myArray[Symbol.iterator]())

Just for the sake of it, here is an example using an ES6 generator function to iterate over an array's contents. You would continue to call generator.next() inside a setInterval() until you are done iterating over the entire array, in which case, you clear the interval and you're done.

var myArr = [0,1,2,3,4];

function* iterateOverArray (arr) {
  var i = 0;
  while (i < arr.length) {
    yield arr[i++];
  }
}

var generator = iterateOverArray(myArr);

var interval = setInterval(function () {
  var nxt = generator.next();
  if (!nxt || nxt.done) {
    clearTimeout(interval);   
  }
  else {
    console.log(nxt.value);
  }
}, 1000);

I wanted to do this as well, this is what I tried in my code:

array=[];

setInterval(mediaTweet, 1000 *60 *2)// every 2min

function mediaTweet () {

let tweet = { status: array[index++ % array.length]
}

 T.post('statuses/update', tweet, tweeted); 
}
Related