When you use const showTime = document.querySelector("p#time");
are you sure the DOM tree has been rendered?
If your DOM tree has not been rendered but you call it, document.querySelector("p#time")
will return null
, and it will clearInterval and it will return
immediately.
So to fix it, you should set the event to call back every time the DOM tree is finished rendering, and will use the DOMContentLoaded
event.
Suggested code:
document.addEventListener("DOMContentLoaded", () => {
const showTime = document.querySelector("p#time");
const intervalId = setInterval(() => {
if (!showTime) {
clearInterval(intervalId);
return;
}
showTime.innerText = new Date().toLocaleTimeString();
}, 1000);
});