日本語

How to Build an Analog Clock with Moving Hands in React

​​React​Playwright,SVG,TypeScript

To draw an analog clock, calculate the hour, minute, and second hand angles from a Date, then rotate SVG lines with transform="rotate(angle centerx centery)". To move the hands, keep the current time in state and update it every time the second changes. If you update with setInterval(…, 1000), the display can lag by almost a full second at most. If you calculate the time until the next second boundary and wait for it with setTimeout, the lag almost disappears.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, and ran them with Playwright. To set specific times, I used Playwright's page.clock to pause and advance the browser clock. I did not test Firefox, Safari, mobile browsers, screen reader announcements, or behavior in background tabs.

On a white dial with the numbers 1 to 12 and 60 tick marks, the black hour and minute hands and the pink second hand point to 10:09:56. At first the second hand jumps one tick at a time every second, and then it reaches 10:10. When the cursor presses the "Move the second hand smoothly" checkbox, that label briefly turns bold pink and the checkbox is checked. After that, the second hand keeps moving slightly at a time without stopping
The second hand moves once per second, and after the checkbox is pressed it moves smoothly. The black bar at the bottom (showing the time), the cursor, the ring shown on press, and the pink label flash are overlays added for the GIF. The labels in the image are in Japanese.

Calculating the Hand Angles from the Time

Every hand's angle is measured clockwise from the 12 o'clock position as 0 degrees. I put the calculation in the following function, separate from React.

ts
export type HandAngles = { hour: number; minute: number; second: number };

// Returns the needle angle in degrees (0 degrees at 12 o'clock, measured clockwise).
// If smooth is true, the second hand also advances by the milliseconds part.
export function handAngles(date: Date, smooth = false): HandAngles {
  const s = date.getSeconds() + (smooth ? date.getMilliseconds() / 1000 : 0);
  const m = date.getMinutes() + s / 60;
  const h = (date.getHours() % 12) + m / 60;
  return { hour: h * 30, minute: m * 6, second: s * 6 };
}

The second and minute hands complete a full circle in 60 units, so they move 6 degrees per second (or per minute). The hour hand completes a full circle in 12 hours, so it moves 30 degrees per hour.

I add the seconds to the minutes and the minutes to the hours as fractions. Without this, the hour hand would jump 30 degrees only once an hour, so at 9:45 it would still point at the 9. getHours() returns 0 to 23, so I take the remainder after dividing by 12. This makes 15:00 point in the same direction as 3:00.

I calculated the angles for several times in Node.js (run with TZ=Asia/Tokyo).

text
03:00:00.000 カチカチ: 時針 90.00度 / 分針 0.00度 / 秒針 0.00度
06:30:00.000 カチカチ: 時針 195.00度 / 分針 180.00度 / 秒針 0.00度
09:45:30.000 カチカチ: 時針 292.75度 / 分針 273.00度 / 秒針 180.00度
10:09:50.700 カチカチ: 時針 304.92度 / 分針 59.00度 / 秒針 300.00度
             なめらか: 時針 304.92度 / 分針 59.07度 / 秒針 304.20度
15:00:00.000 カチカチ: 時針 90.00度 / 分針 0.00度 / 秒針 0.00度

The hour hand at 6:30 is at 195 degrees, between the 6 and the 7. 15:00 gave 90 degrees, the same as 3:00. The rows marked katikati (the Japanese onomatopoeia for ticking) are the output with smooth set to false, and the rows marked nameraka (the Japanese word for "smooth") are the output with smooth set to true. With false, the milliseconds are truncated, so the second hand points exactly at a tick mark.

Drawing the Dial and Hands with SVG

I draw the clock as an SVG with viewBox="0 0 200 200". The center is at (100, 100). Each hand is drawn as a <line> standing straight up toward 12 o'clock, and a transform attribute rotates it around the center.

tsx
import { handAngles } from './clock';
import { useNow } from './useNow';

type Props = { smooth?: boolean; size?: number };

// Position of the dial numeral (from center 100,100 at radius r, at deg degrees clockwise from 12 o'clock).
function polar(deg: number, r: number) {
  const rad = (deg * Math.PI) / 180;
  return { x: 100 + r * Math.sin(rad), y: 100 - r * Math.cos(rad) };
}

export function AnalogClock({ smooth = false, size = 200 }: Props) {
  const now = useNow(smooth);
  const { hour, minute, second } = handAngles(now, smooth);
  const label = `${now.getHours()}時${now.getMinutes()}分`;

  return (
    <svg viewBox="0 0 200 200" width={size} height={size} role="img" aria-label={label}>
      <circle cx="100" cy="100" r="96" fill="#fff" stroke="#1f2a30" strokeWidth="4" />
      {Array.from({ length: 60 }, (_, i) => (
        <line
          key={i}
          x1="100" y1="8" x2="100" y2={i % 5 === 0 ? 20 : 14}
          stroke="#1f2a30" strokeWidth={i % 5 === 0 ? 3 : 1}
          transform={`rotate(${i * 6} 100 100)`}
        />
      ))}
      {Array.from({ length: 12 }, (_, i) => {
        const { x, y } = polar((i + 1) * 30, 70);
        return (
          <text key={i} x={x} y={y} textAnchor="middle" dominantBaseline="central" fontSize="16" fill="#1f2a30">
            {i + 1}
          </text>
        );
      })}
      <line className="hour" x1="100" y1="112" x2="100" y2="50" stroke="#1f2a30" strokeWidth="6" strokeLinecap="round"
        transform={`rotate(${hour} 100 100)`} />
      <line className="minute" x1="100" y1="114" x2="100" y2="24" stroke="#1f2a30" strokeWidth="4" strokeLinecap="round"
        transform={`rotate(${minute} 100 100)`} />
      <line className="second" x1="100" y1="120" x2="100" y2="16" stroke="#d85878" strokeWidth="2"
        transform={`rotate(${second} 100 100)`} />
      <circle cx="100" cy="100" r="4" fill="#d85878" />
    </svg>
  );
}

As described in MDN's explanation of the SVG transform attribute, rotate(a x y) rotates by a degrees around the point (x, y). If you omit x and y, it rotates around the origin of the user coordinate system. In this clock, whose viewBox starts at 0 0, that is the top-left corner. Each hand line starts slightly below the center (y1 is 112 to 120) and extends a short distance past it on the other side.

SVG coordinates increase downward, so a positive angle rotates clockwise. In Chromium in the test environment, I read where each hand tip was on screen relative to the center (right and down are positive; the clock was displayed at 240px, so one SVG unit is 1.2px).

text
03:00:00 時針 90度 先 (60.0, 0.0) / 分針 0度 先 (0.0, -91.2) / 秒針 0度 先 (0.0, -100.8)
06:30:00 時針 195度 先 (-15.5, 58.0) / 分針 180度 先 (0.0, 91.2) / 秒針 0度 先 (0.0, -100.8)
09:45:30 時針 292.75度 先 (-55.3, -23.2) / 分針 273度 先 (-91.1, -4.8) / 秒針 180度 先 (0.0, 100.8)

At 3:00 the hour hand points straight right, and at 6:30 the minute hand points straight down. For the tick marks, I used the same approach: a short line standing at 12 o'clock, rotated by 6 degrees each time, for 60 lines. Every fifth line is thicker and longer.

Rotating a <text> element would tilt the characters too, so I calculate the positions of the numbers with polar. For a point at radius r, measured clockwise from 12 o'clock by deg degrees, x is 100 + r × sin and y is 100 − r × cos.

I gave the whole SVG role="img" and an aria-label, using a label made of the hour and minute, such as 10 and 9, with the Japanese characters for hour and minute between them, as the name. MDN's explanation of the img role says that when an SVG is embedded, giving the outer <svg> role="img" and a label makes screen readers treat it as a single image described by its label, without reading each child node one by one. I made the name only go down to the minute, so the attribute value changes once a minute. In the test environment, when I opened the clock at 3:00, 6:30, and 9:45:30, the names of the role="img" elements were the Japanese labels for 3:00, 6:30, and 9:45, respectively (each one is the hour and minute, with the Japanese characters for hour and minute between them).

Updating the Current Time at Each Second Boundary

The current time is held in state by the custom hook useNow. When smooth is false, it updates every time the second changes.

ts
import { useEffect, useState } from 'react';

// Returns the current time. If smooth, updates on every screen redraw; otherwise updates whenever the second changes.
export function useNow(smooth: boolean): Date {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    let id = 0;
    if (smooth) {
      const loop = () => {
        setNow(new Date());
        id = requestAnimationFrame(loop);
      };
      id = requestAnimationFrame(loop);
      return () => cancelAnimationFrame(id);
    }
    // Waits until the next second boundary to update, then waits for the following boundary again.
    const tick = () => {
      const d = new Date();
      setNow(d);
      id = window.setTimeout(tick, 1000 - d.getMilliseconds());
    };
    tick();
    return () => clearTimeout(id);
  }, [smooth]);
  return now;
}

tick reads the milliseconds of the current time, waits 1000 - milliseconds (the time until the next second boundary), and then calls itself again. It recalculates the wait from the time at each call, so even if a call is delayed, the next one returns to the boundary.

I compared this with updating using setInterval(() => setNow(new Date()), 1000). With Playwright's page.clock, I froze the browser clock at 10:09:50.700, opened the page, advanced the clock in small steps, and read the second the hand was pointing to.

Actual time Synced to boundary (code in this article) setInterval at 1000ms
10:09:50.700 50 50
10:09:51.000 51 50
10:09:51.699 51 50
10:09:51.700 51 51
10:09:52.000 52 51
10:09:53.000 53 52

With the setInterval approach, the page was opened at .700 seconds, so updates always fire at .700 seconds too. As a result, for 0.7 seconds after the real second changes, the hand keeps pointing at the previous second. How large the lag is depends on the milliseconds at which the page was opened, and it ranges from 0 to nearly 1 second.

I also ran the test for 10 seconds without freezing the clock, using the real time. These are the millisecond values at which the second hand updated.

text
記事のコード:
  更新 10回 / 更新したときのミリ秒: 1, 2, 1, 2, 1, 2, 1, 2, 1, 1
setInterval で 1000ms ごと:
  更新 10回 / 更新したときのミリ秒: 872, 871, 871, 870, 870, 871, 871, 871, 870, 870

With the code in this article, the display changed 1 to 2 ms after the second changed. With setInterval, each update came about 0.87 seconds after the second changed.

The wait time of setTimeout is not always exactly the time you specify. MDN's explanation of setTimeout() lists reasons the wait can be longer than specified. For example, in background tabs, Chrome and desktop Firefox set the minimum wait to 1 second. Even in this case, tick reads the time when it is called, so the hands point to the time at which it was called.

The function returned from useEffect stops the timer. As described in React's useEffect reference, React calls this function when a value in the dependency array (here, smooth) changes and when the component is removed from the screen.

Moving the Second Hand Smoothly with requestAnimationFrame

When smooth is true, the time is updated each time requestAnimationFrame redraws the screen, and handAngles adds the milliseconds to the second hand's angle. According to MDN's explanation of requestAnimationFrame(), the callback is called before the next repaint, and the number of calls per second is usually the same as the screen's refresh rate. To keep it running, the callback calls requestAnimationFrame again.

In the test environment, I toggled smooth with the checkbox and counted how many times the transform attribute of the second hand changed per second.

text
  オフ: 1秒間の秒針の更新回数 1
  オン: 1秒間の秒針の更新回数 60 / 最初の5回 rotate(24.576 100 100) rotate(24.678000000000004 100 100) rotate(24.78 100 100) rotate(24.882 100 100) rotate(24.978 100 100)
  オフに戻す: 1秒間の秒針の更新回数 1

When on, the second hand advanced by about 0.1 degrees each time, 60 times per second. When turned off again, it went back to 1 update per second, so cancelAnimationFrame stopped the per-redraw updates.

With this approach, AnalogClock re-renders 60 times per second, and the JSX for the tick marks and numbers is rebuilt each time. However, as described in React's official documentation on render and commit, React only changes the DOM nodes that differ between renders.

Adding a CSS transition to the Second Hand Makes It Turn Backward at 0 Seconds

I tried to make the once-per-second movement of the second hand look a little smoother by adding a CSS transition. But then, when going from 59 seconds to 0 seconds, the second hand turns counterclockwise by almost a full circle.

css
.second { transition: transform 0.3s; }

In Chromium in the test environment, this transition also applied when the SVG transform attribute changed. The second hand's angle at 59 seconds is 354 degrees, and at 0 seconds the angle goes back to 0 degrees. The transition connects 354 to 0 by decreasing the number, so the second hand turns counterclockwise by almost a full circle. Reading the apparent angle partway through, I got the following (shown in the range -180 to 180 degrees).

text
  transition の途中の見た目の角度(-180〜180度で表示): 0ms -6.0度 / 75ms -150.6度 / 150ms 69.9度 / 225ms 14.0度 / 300ms 0.0度

Within 0.3 seconds, the hand went from just before 12 o'clock (-6 degrees), counterclockwise past the 6 o'clock position, and back to 12 o'clock. The minute and hour hands also return from just under 360 degrees to 0 degrees. The minute hand returns to 0 at the top of each hour, and the hour hand returns at 0:00 and 12:00. Calculated in Node.js, the minute hand at 23:59:59.999 is at 359.90 degrees, and at 0:00:00 it is 0 degrees.

I added the same .minute { transition: transform 0.3s; } to the minute hand, and used Playwright's page.clock to advance the time from 10:59:59 to 11:00:00.

text
  10:59:59: transform 属性 rotate(359.9 100 100) / 見た目の角度 -0.1
  11:00:00 になった直後: transform 属性 rotate(0 100 100) / 動いているアニメーション 1
  transition の途中の見た目の角度(-180〜180度で表示): 0ms -0.1度 / 75ms -147.1度 / 150ms 71.1度 / 225ms 14.2度 / 300ms 0.0度

When the minute hand reached 0 minutes, it also turned counterclockwise by almost a full circle, just like the second hand.

The code in this article does not use a transition. It uses two movements: a jump at each second, and a smooth movement with requestAnimationFrame.

​Posted by 86