A clock app is the smallest project that teaches real-time updates: read the time, draw it, and do it again every second. Build both an analogue face and a digital readout in one page, and you will learn the Date object, CSS transforms, and setInterval — three things every front-end developer uses daily.
The digital clock is five lines. Read the hours, minutes, and seconds, pad them to two digits, and update the text once a second:
function updateDigital() {
const now = new Date();
const pad = (n) => String(n).padStart(2, "0");
document.getElementById("digital").textContent =
`${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
}
setInterval(updateDigital, 1000);
updateDigital();
The analogue clock is the same data drawn differently. Each hand is a div rotated around its base. The angles are simple maths: the second hand moves 6 degrees per second (360/60), the minute hand 6 degrees per minute plus a fraction for the seconds, and the hour hand 30 degrees per hour plus a fraction for the minutes:
function updateAnalogue() {
const now = new Date();
const seconds = now.getSeconds();
const minutes = now.getMinutes();
const hours = now.getHours() % 12;
const secondDeg = seconds * 6;
const minuteDeg = minutes * 6 + seconds * 0.1;
const hourDeg = hours * 30 + minutes * 0.5;
document.getElementById("second-hand").style.transform = `rotate(${secondDeg}deg)`;
document.getElementById("minute-hand").style.transform = `rotate(${minuteDeg}deg)`;
document.getElementById("hour-hand").style.transform = `rotate(${hourDeg}deg)`;
}
setInterval(updateAnalogue, 1000);
updateAnalogue();
Two CSS details make it work. First, each hand needs transform-origin at its bottom so it rotates around the centre of the clock face, not its own middle. Second, the clock face numbers are positioned with their own rotations — 30 degrees apart, each counter-rotated so the digits stay upright:
.hand {
position: absolute;
bottom: 50%;
left: 50%;
transform-origin: bottom center;
border-radius: 4px;
}
#hour-hand { width: 6px; height: 25%; background: #111; }
#minute-hand { width: 4px; height: 35%; background: #333; }
#second-hand { width: 2px; height: 40%; background: #e11d48; }
A common beginner mistake is calling setInterval twice for the same job or updating the DOM more often than needed. One interval that updates both the digital and analogue displays is cleaner, and updating once a second is plenty — the human eye cannot see a smoother analogue second hand without sub-second ticks anyway.
Ways to extend it: add a stopwatch mode with start, stop, and lap buttons, add a countdown timer with an alarm sound from the Web Audio API, add a dark/light theme toggle, or let the user pick a timezone and show that city's time alongside their own. The pattern — read a value, render it, repeat on a timer — is the same pattern behind live dashboards, stock tickers, and countdown pages.
Top comments (0)