最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Sep 21, 2017 at 22:41 user8142459user8142459 2
  • 1 Have you tried anything yourself? – Etheryte Commented Sep 21, 2017 at 22:45
  • hint: use setTimeout or setInterval – Jaromanda X Commented Sep 21, 2017 at 22:45
Add a ment  | 

4 Answers 4

Reset to default 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)

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); 
}
发布评论

评论列表(0)

  1. 暂无评论