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
3,600,000
is not valid milliseconds. Use3600000
or60*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 anif (counter=> length) counter = 0;
The
=>
is an Arrow_functions making the constructfunctionally equivalent (there are a few other things) to
Change the 2000 to 3600000 if you need every hour
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".
Btw, while investigating this, I was down on my knees, when found out that it will work with
let i = 0
and will not withvar i = 0
.here is the explanation why https://medium.com/@axionoso/watch-out-when-using-settimeout-in-for-loop-js-75a047e27a5f.