简体   繁体   中英

JavaScript “document.getElementById().innerHTML” waits in loop

I have a JS program which cycles through a list of words and sets the text of the

<span id="changing"></span>

To the current item in the list. Here's my code:

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;
    });
  }
}

How can I wait 1 second each time it changes the word? (also, this doesn't seem to do anything, so if you could help with that, that would be absolutely amazing)

You can do this with a little bit of recursion, and using the setTimeout function.

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);

Or you could use setInterval to acheive the same thing

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);

With that specific implementation however, the index variable would be open to change from anything else in that scope. The setTimeout method encapsulates the index value so that it can't be changed externally.

There is a built-in javascript function called setInterval() which infinitely does a function in intervals of n in milliseconds. Applying this to your situation:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM