JavaScript - 25
JavaScript - 25: Digital Clock
Create a digital clock that shows the current hours, minutes, and seconds.
Your challenge: Read the current time with JavaScript, format it as HH:MM:SS, and update the clock every second.
Get the current time
Use: const now = new Date();
Then read the time with: getHours(), getMinutes(), and getSeconds().
Add leading zeros
A digital clock usually shows 09 instead of 9.
You can check whether a value is below 10 and add a zero when needed.
Update the clock
Use: setInterval(updateClock, 1000);
This runs updateClock() every 1000 milliseconds, or once per second.
Also call updateClock() once immediately so the clock does not wait one second before showing the current time.
Try it: Watch the seconds change and notice when the minutes update.
Good JavaScript habit: Put repeated work inside a function, then use setInterval() to run that function on a schedule.
👀 Show Solution
const clock = document.getElementById("clock");
function updateClock() {
const now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
clock.textContent = `${hours}:${minutes}:${seconds}`;
}
setInterval(updateClock, 1000);
updateClock();new Date() gets the current time, and setInterval() updates the display once every second.
