79656814

Date: 2025-06-07 09:32:27
Score: 1
Natty:
Report link

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);
});
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): When you useare you
  • Low reputation (1):
Posted by: Hieu Bosco