5

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?

2
  • 1
    Have you tried anything yourself? Commented Sep 21, 2017 at 22:45
  • hint: use setTimeout or setInterval Commented Sep 21, 2017 at 22:45

4 Answers 4

8

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)

Sign up to request clarification or add additional context in comments.

2 Comments

that loops more than once :p
@JaromandaX I've added a new example which stops the logging after the first iteration.
2

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]())

Comments

0

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);

Comments

0

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); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.