我有一个JS程序,它循环浏览单词列表并设置文字
<span id="changing"></span>
到列表中的当前项目。这是我的代码:
const words = [
"Amazing",
"Simple",
"Powerful",
"Extensible",
"Fast",
"Lightweight",
"Integrated",
"Incredible",
];
let num = 0;
function infinite() {
while (num < 1) {
words.forEach((item) => {
document.getElementById("changing").innerHTML = item;
});
}
}
每次更改单词时,我如何等待1秒钟? (此外,这似乎没有任何作用,因此,如果您可以提供帮助,那将绝对令人惊讶)
您可以进行一点递归,并使用setTimeout
功能。
const words = ["Amazing", "Simple", "Powerful", "Extensible", "Fast", "Lightweight", "Integrated", "Incredible"];
function infinite(index) {
if (index === words.length) {
index = 0;
}
document.getElementById("changing").innerHTML = words[index];
setTimeout(() => infinite(index + 1), 1000);
}
infinite(0);
或者您可以使用setInterval
实现相同的功能
const words = ["Amazing", "Simple", "Powerful", "Extensible", "Fast", "Lightweight", "Integrated", "Incredible"];
let index = 0;
function infinite() {
if (index >= words.length) {
index = 0;
}
document.getElementById("changing").innerHTML = words[index];
index++;
}
setInterval(infinite, 1000);
但是,通过该特定实现,index
变量将可以在该范围内进行更改。 setTimeout
方法封装了索引值,因此无法在外部对其进行更改。
有一个称为setInterval()
的内置javascript函数,该函数以毫秒为间隔n
无限地执行该功能。将此应用于您的情况:
const words = ["Amazing", "Simple", "Powerful", "Extensible", "Fast", "Lightweight", "Integrated", "Incredible"];
var index = 0;
setInterval(() => {
document.getElementById("changing").textContent = words[index];
index = (index+1) % words.length;// If index becomes the last element, it will then go to the first element, making a loop
}, 1000); // 1000 ms = 1 s
<span id="changing"></span>