【问题标题】:JavaScript "document.getElementById().innerHTML" waits in loopJavaScript“document.getElementById().innerHTML”在循环中等待
【发布时间】:2020-10-04 09:40:48
【问题描述】:

我有一个 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 秒? (另外,这似乎没有任何作用,所以如果你能提供帮助,那就太棒了)

【问题讨论】:

  • 使用 setInterval
  • infinite 将阻止您的浏览器
  • 使用 setTimeout 可以解决这两个问题。

标签: javascript sleep innerhtml getelementbyid


【解决方案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 方法封装了索引值,使其不能被外部更改。

【讨论】:

    【解决方案2】:

    有一个名为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
    &lt;span id="changing"&gt;&lt;/span&gt;

    【讨论】:

    • 这非常有效。但是您知道是否有任何方法可以使用 CSS transition all ease-in-out 让这看起来更好?
    • 这绝对是可能的,但我不确定你应该使用过渡,而是animation。你在文本之间寻找什么样的动画?
    • 只是一个简单的淡入淡出效果。
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2018-09-25
    相关资源
    最近更新 更多