skip to Main Content

I have been trying to make a loop of messages that change every hour (One is visible at a time) I’m decent at HTML, but I’m pretty bad at JS. (Message should go in h3)

I tried to link my JS loop into a HTML text element, but I failed.

h3 = document.createElement("h3");
var messages = "Message 1", "Message 2", "Message 3", "Message 4", "Message 5", "Message 6";
var counter = 0;

function myLoop() {
  setTimeout(myLoop, 3, 600, 000);
  document.getElementById("Message")
  document.body.appendChild(h3);
}
myLoop();
<h3>
  <h3 id="Message"></h3>
</h3>

2

Answers


    1. do not wrap headers in headers
    2. It looks like you wanted an Array of messages. I show you below how to make such a thing
    3. You would not need to use appendChild when the element already exists on the page
    4. 3,600,000 is not valid milliseconds. Use 3600000 or 60*60*1000

    In my code below I use an eventListener to wait with the execution until the html elements on the page are available

    The statement (counter++)%len will start at 0 and wrap at length of array of messages using the remainder operator %. It saves an if (counter=> length) counter = 0;

    The => is an Arrow_functions making the construct

    const functionName (parameter) => { };
    

    functionally equivalent (there are a few other things) to

    function functionName(parameter) { };
    

    Change the 2000 to 3600000 if you need every hour

    const messages = ["Message 1", "Message 2", "Message 3", "Message 4", "Message 5", "Message 6"];
    const len = messages.length;
    let counter = 0;
    
    window.addEventListener("DOMContentLoaded", () => { // when the page has loaded and the h3 is available
      const h3 = document.getElementById("Message");
      const myLoop = () => h3.textContent = messages[(counter++) % len]; // loop and wrap
      myLoop(); // run once immediately
      setInterval(myLoop, 2000); // then run every 2 seconds
    });
    <div>
      <h3 id="Message"></h3>
    </div>
    Login or Signup to reply.
  1. Use this soulution if you want to have different time intervals between messages, but if you are fine with same repeated interval he solution above is more of "best practice".

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
    
        <h3 id="Message"></h3>
        <script>
            var h3elem = document.getElementById('Message');
            h3elem.innerHTML = "Starting text"
            function myLoop() {
                let messages = ['Message 1', 'Message 2', 'Message 3', 'Message 4', 'Message 5', 'Message 6'];
                let timeouts = [1000, 2000, 3000, 5000, 6000, 7000];
                for (let i = 0; i< messages.length; i++) {
                    setTimeout(() => {
                        h3elem.innerHTML = messages[i]
                        console.log("timeout", i)
                    }, timeouts[i])
          
                }
            }
            myLoop();
        </script>
    </body>
    
    </html>
    

    Btw, while investigating this, I was down on my knees, when found out that it will work with let i = 0 and will not with var i = 0.
    here is the explanation why https://medium.com/@axionoso/watch-out-when-using-settimeout-in-for-loop-js-75a047e27a5f.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search