JavaScript "document.getElementById().innerHTML" 循环等待

JavaScript "document.getElementById().innerHTML" waits in loop

我有一个 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>