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 < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 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.
Leave a Reply