我有很多国家/地区。我想从开始到结束每两秒打印一次数组的元素或国家/地区。
尝试使用 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/