Digital Clock

Why? Learn Date() object and updating UI with setInterval().

<!DOCTYPE html>
<html>
<head>
  <title>Digital Clock</title>
</head>
<body>
  <h2 id="clock"></h2>

  <script>
function showTime() {
  let time = new Date();
  let hours = time.getHours();
  let minutes = time.getMinutes();
  let seconds = time.getSeconds();
  // Format with leading zeros
  hours = (hours &lt; 10 ? "0" : "") + hours;
  minutes = (minutes &lt; 10 ? "0" : "") + minutes;
  seconds = (seconds &lt; 10 ? "0" : "") + seconds;
  document.getElementById("clock").innerText = ${hours}:${minutes}:${seconds};
}
setInterval(showTime, 1000); // update every second
showTime(); // call immediately
</script> </body> </html>

Explanation:

  • new Date() → gets current time.
  • setInterval() updates the time every second.
  • Updates <h2> text with formatted time.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *