Search code examples
javascriptsleepinnerhtmlgetelementbyid

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)


Solution

  • 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>