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

标签 javascript for-loop timer

我有很多国家/地区。我想从开始到结束每两秒打印一次数组的元素或国家/地区。

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

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

function printCountries() {
    for (i = 0; i < countries.length; i++) {
        document.write(countries[i]);
        }
    } 

setInterval(printCountries, 2000);

我希望从头到尾打印数组的元素,每两秒打印一个新元素。相反,整个数组会一次性打印出来。我该如何解决这个问题?

最佳答案

你不需要循环。该间隔充当循环机制,因为它每 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>

关于javascript - 使用计时器以给定的时间间隔打印数组的各个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392495/

相关文章:

javascript - 如何使增强的 for 循环只查看实际的数组内容

java - 为什么我的数组包含相同的元素?

python - python中的迭代问题

python - 如果值在Python中的字典中匹配,则快速子集数组

使用闭包在循环中创建的javascript计时器或间隔

javascript - 创建一个新选项并使用 mootools 1.2 注入(inject)选择框

javascript - ReactJS:更新 props - 将 2 个键:值对的 17 个对象数组转换为具有 3 个键:值对的数组

javascript - 具有延迟、重置和重新启动功能的计时器? jQuery

c - 如何在 C 中跟踪计时器或警报或设置可跟踪计时器

javascript - 为什么下面的 jQuery 选择器不返回两个元素?