使用计时器以给定间隔打印数组的单个元素

时间:2019-01-27 20:19:59

标签: javascript for-loop timer

我有很多国家。我想从头到尾每两秒钟打印一次数组的元素或国家。

尝试使用setInterval()函数和for循环来完成此操作。

horsemen(Man, Horse, Heads, Legs) :-
   between(0, Legs, Man),
   between(0, Legs, Horse),
   Legs is 2*Man + 4*Horse, Heads is Man + Horse.

我希望数组的元素将从头到尾打印,每两秒钟打印一次新元素。相反,整个数组会一次全部打印。我该如何解决?

2 个答案:

答案 0 :(得分:2)

您不需要循环。该间隔充当循环机制,因为它每2秒连续运行一次。

您的函数只需要基于一个索引打印一个数组元素,该索引在每次调用该函数时都会递增。

查看内联评论:

let output = document.querySelector("div");

var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama',         
                 'Dominican Republic', 'Brazil', 'Germany', 'France', 
                 'Portugal','Spain', 'the Netherlands']; 

let timer = null; // Will hold a reference to the timer
let index = 0;    // Keeps track of which array element to show next

function printCountries() {
   // Set the contents of the output element (the <div>) to its old
   // contents, plus the next country name and an HTML <br>. This is
   // what makes the contets of the <div> grow each time a new country
   // is iterated.
   output.innerHTML = output.innerHTML + countries[index] + "<br>";
   // Check to see if we've reached the end of the array.
   if(index === countries.length-1){
     clearInterval(timer);  // Cancel the timer
   } else {
     index++; // Increment the index so that the next time, we get the next country
   }
} 

// You'll want to stop the interval when you're done iterating the array
// so you need to set u a reference to it to refer to later.
timer = setInterval(printCountries, 2000);
<div></div>

答案 1 :(得分:1)

问题是,您每2秒调用一次printCountries函数,并且每次调用printCountries函数时都会打印整个countries数组。

要获得所需的结果,可以使用generator函数

const countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama',
             'Dominican Republic', 'Brazil', 'Germany', 'France',
             'Portugal','Spain', 'the Netherlands'];

function* getCountry() {

  for(let i=0; i<countries.length; i++) {
     // clear the interval if current index is the last index of the array
    if(i === countries.length - 1) {
        clearInterval(interval);
    }

    yield countries[i];
  }
}

let country = getCountry();

const interval = setInterval(() => console.log(country.next().value), 2000);
.as-console-wrapper { max-height: 100% !important; top: 0; }

您可以将清除间隔的逻辑移出generator函数以简化操作

const countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama',
             'Dominican Republic', 'Brazil', 'Germany', 'France',
             'Portugal','Spain', 'the Netherlands'];

function* getCountry() {
  for(let i=0; i<countries.length; i++) {
    yield countries[i];
  }
}

let country = getCountry();
let result;

const interval = setInterval(() => {
   result = country.next();
   result.done === false ? console.log(result.value) : clearInterval(interval);
}, 2000);
.as-console-wrapper { max-height: 100% !important; top: 0; }