Connect JS message loop in HTML header
P粉731861241
2023-09-05 10:55:30
<p>I've been trying to make a message loop that changes every hour (only displays one at a time), I'm ok with HTML but not so good with JS. (The message should be placed in h3 tag)</p>
<p>I tried to link my JS loop into an HTML text element but failed. </p>
<p>
<pre class="brush:js;toolbar:false;">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();</pre>
<pre class="brush:html;toolbar:false;"><h3>
<h3 id="Message"></h3>
</h3></pre>
</p>
3,600,000
is not a valid number of milliseconds. Use3600000
or60*60*1000
In my code, I use eventListener to wait for the html element on the page to be available before executing
Statement
(counter )%len
will start at 0 and loop at the length of the message array using the remainderoperator%
. It avoidsif (counter=> length) counter = 0;
=>
is an arrow function, constructed as followsFunctionally equivalent to (and a few other things)
If you need to execute it every hour, please change 2000 to 3600000