Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 156 ยท Projects

Project: Digital and Analog Clock, Stopwatch

Build a digital clock with 12/24-hour and time zones, an SVG analog clock, and a stopwatch with laps. Learn setTimeout, requestAnimationFrame and performance.now().

Clocks are the classic first "live" web project: something on the page changes by itself, every second, forever. They're also a great way to learn how JavaScript really handles time, because three questions come up right away. How do I get the current time? How often should I redraw? And why does my stopwatch run slow when I switch tabs?

In this project you'll build three things: a digital clock with a 12/24-hour switch and a few time zones, an analog clock drawn in SVG with a smoothly sweeping second hand, and a stopwatch with laps and keyboard shortcuts. Along the way you'll use Date, Intl.DateTimeFormat, setTimeout, requestAnimationFrame and performance.now(), and you'll learn the one rule that keeps every timer honest.

It builds on Dates, setTimeout and setInterval, Creating and Removing Elements and Bubbling, Capturing and Delegation.

The one rule: timers are triggers, not clocks

setInterval(fn, 1000) does not promise to run fn exactly every second. The browser runs it about every second, but it may be late: a busy page delays it, and background tabs are throttled (often to once per second or even once per minute). If you write seconds++ inside the callback, your clock slowly drifts and then falls far behind when the tab is hidden.

The fix is to treat a timer only as a trigger to look at a real clock and redraw:

  • To show the time, read new Date() every time. Never count ticks.
  • To measure elapsed time, store a start timestamp and subtract it from performance.now().

With that rule, a late timer only means a late redraw. The number on the screen is always correct the moment it's drawn.

Step 1: Formatting time

All three projects need to turn numbers into text such as 07:05:09 or 01:23.45. That's pure logic with no DOM, so write it first and test it in the console. Two helpers do most of the work: pad(), which adds leading zeros with padStart(), and to12Hour(), which converts 0 to 12 and 13 to 1 with the h % 12 || 12 trick.

JS Step 1: Time-formatting helpers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that formatElapsed() works in whole centiseconds (hundredths of a second) and always rounds down. A stopwatch that rounded up would show 00:01.00 before a full second had passed.

Step 2: A digital clock

The digital clock has to answer one new question: when do we redraw? Calling setInterval(tick, 1000) right after page load would tick at :00.730, :01.730 and so on, so the display would change almost a second off from the real second boundary. A better pattern is a chain of setTimeout calls, each one scheduled to fire exactly on the next whole second:

JavaScript
function scheduleNext() {
  setTimeout(() => { render(); scheduleNext(); }, 1000 - (Date.now() % 1000));
}

Date.now() % 1000 is how far into the current second we are, so 1000 minus that is the wait until the next one. Because every delay is recalculated, small delays never pile up.

For time zones you don't need a library. Intl.DateTimeFormat accepts any IANA zone name such as "Asia/Tokyo" and its formatToParts() method returns the hours, minutes and seconds for that zone as separate pieces. The date line uses toLocaleDateString(), so it follows the visitor's language.

Step 2: Digital clock with time zones

Pick Tokyo and watch the date line: when it's late evening where you are, Tokyo is already on tomorrow's date. That's why the date has to be formatted in the same zone as the time.

The role="timer" attribute with aria-live="off" tells screen readers this is a clock but not to announce every second, which would be unbearable. Never put aria-live="polite" on something that changes every second.

Step 3: An analog clock in SVG

An analog clock is geometry. Draw a circle, 60 tick marks and three lines (the hands), then rotate each hand to an angle worked out from the time. SVG is perfect for this because it scales without blurring and you can rotate any element with a transform.

The angles are:

Hand One full turn Degrees Angle formula
Hour 12 hours 30 per hour (hours % 12 + minutes / 60) * 30
Minute 60 minutes 6 per minute (minutes + seconds / 60) * 6
Second 60 seconds 6 per second (seconds + milliseconds / 1000) * 6

Adding the smaller unit (minutes / 60 for the hour hand) is what makes the hour hand creep gradually between numbers instead of jumping on the hour.

For the second hand, one update per second makes it tick like a quartz clock. To make it sweep smoothly, redraw on every screen frame with requestAnimationFrame(). The browser calls your function right before each repaint (usually 60 times a second) and pauses it automatically in hidden tabs, so it costs nothing when nobody is looking. The code reads new Date() on each frame, following the rule from the start of the lesson. The checkbox switches between smooth and ticking, and it starts out ticking for visitors who ask their system for reduced motion.

Step 3: SVG analog clock

The numbers are placed with trigonometry: for the hour n, the angle from 12 o'clock is n * 30 degrees, so x = sin(angle) * radius and y = -cos(angle) * radius (SVG's y axis points down, hence the minus). The -cos also explains why the hands are drawn pointing up at rotation 0: a rotation of 0 degrees then means "12 o'clock".

Redrawing 60 times a second is overkill if you only show the hour and minute hands. A ticking clock needs one redraw per second: use the chain of setTimeout calls from Step 2. Use requestAnimationFrame only when you need smooth motion.

Step 4: A stopwatch with laps

A stopwatch has three pieces of state: whether it's running, the performance.now() value at the last start, and how many milliseconds had already elapsed before that start. The current time is always computed:

JavaScript
elapsed = elapsedBefore + (performance.now() - startedAt);

Pausing adds the latest stretch to elapsedBefore and stops the loop. Resuming sets a new startedAt. Because the display is derived from those values, it can't drift, and it stays correct even if the page is hidden for minutes.

performance.now() is better than Date.now() here because it's monotonic: it only ever increases, even if the user's system clock is adjusted while the stopwatch runs.

Laps are just recorded totals. Each lap's own time is its total minus the previous total. Once there are at least three laps, the fastest is highlighted green and the slowest red.

The left button toggles Start and Stop. The right button is Lap while running and Reset when stopped, a common pattern that saves space and prevents accidental resets. Keyboard shortcuts Space, L and R call the same functions as the buttons.

Step 4: Stopwatch with laps

Start it, take a few laps, stop, and press Resume: the time continues from where it stopped. Then switch to another browser tab for ten seconds and back. The display jumps to the correct value, because it's computed from timestamps, not counted.

One subtle detail: Math.min(...times) and Math.max(...times) need at least one lap, which is why renderLaps() is only called right after a lap was added.

Where to go from here

  • Countdown timer. Store a target endsAt = performance.now() + duration and show endsAt - performance.now(). Play a sound at zero with the Web Audio and media APIs.
  • Pomodoro timer. Alternate a 25-minute countdown with a 5-minute break and keep a counter of completed rounds.
  • Alarm clock. Compare Date.now() with a chosen time on every tick, and guard against firing twice.
  • World clock. Show a grid of analog clocks, one per time zone, by passing the zone to getParts().
  • Persist laps. Save laps to localStorage (outside the sandbox) as shown in localStorage and sessionStorage.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why shouldn't a clock be built by incrementing a seconds counter inside setInterval?

    Browsers delay timers on busy pages and throttle them in background tabs. Read the real time (new Date() or performance.now()) on each redraw instead of counting ticks.
  2. 2. What does 1000 - (Date.now() % 1000) calculate?

    Date.now() % 1000 is how far into the current second we are. Subtracting it from 1000 gives the wait until the next boundary, so each redraw lines up with the real second.
  3. 3. Which angle is correct for the hour hand at 3:30?

    (3 + 30 / 60) * 30 = 105. The half hour moves the hour hand halfway between the 3 and the 4.
  4. 4. Why does the stopwatch use performance.now() and not Date.now()?

    performance.now() is monotonic, so changes to the system clock (time sync, daylight saving, manual changes) can't make the stopwatch jump or run backwards.
  5. 5. What is requestAnimationFrame() best used for?

    The browser calls your callback before each repaint and pauses it in hidden tabs, which makes it ideal for smooth animation and wasteful for once-per-second updates.

Summary

  • A timer is a trigger to redraw, not a clock. Read new Date() to show time and subtract performance.now() values to measure it.
  • Chain setTimeout(fn, 1000 - (Date.now() % 1000)) to redraw exactly on the second without drift.
  • Intl.DateTimeFormat with timeZone and formatToParts() gives times for any IANA time zone; hours % 12 || 12 converts to 12-hour time.
  • Analog hands are rotations: hour (h % 12 + m / 60) * 30, minute (m + s / 60) * 6, second (s + ms / 1000) * 6.
  • Use requestAnimationFrame for smooth motion, and respect prefers-reduced-motion.
  • A stopwatch stores startedAt and elapsedBefore, derives the display from them, and works out lap times by subtracting totals.

Next: Project: Tic-Tac-Toe and Rock-Paper-Scissors.