P粉2390894432023-09-06 09:59:38
3,600,000
is not a valid number of milliseconds. Use 3600000
or 60*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 avoids if (counter=> length) counter = 0;
=>
is an arrow function, constructed as follows
const functionName (parameter) => { };
Functionally equivalent to (and a few other things)
function functionName(parameter) { };
If you need to execute it every hour, please change 2000 to 3600000
const messages = ["Message 1", "Message 2", "Message 3", "Message 4", "Message 5", "Message 6"];
const len = messages.length;
let counter = 0;
window.addEventListener("DOMContentLoaded", () => { // 当页面加载完成且h3可用时
const h3 = document.getElementById("Message");
const myLoop = () => h3.textContent = messages[(counter++) % len]; // 循环并包装
myLoop(); // 立即执行一次
setInterval(myLoop, 2000); // 然后每2秒执行一次
});
<div>
<h3 id="Message"></h3>
</div>