Skip to the solution
MediumMachine Coding13 min read

Build an Analog Clock

600 views

The problem

Question presented to candidate: "Build an analog clock: a round face with hour, minute and second hands that always show the current time. I would like the second hand to sweep smoothly, but give me a way to switch it to a classic one-tick-per-second movement. Walk me through the angle maths."

Requirements:

  • A clock face with 60 tick marks and the numbers 1 to 12, drawn with SVG.
  • Hour, minute and second hands rotated to the current time; the hour hand moves gradually between numbers, not in jumps.
  • A "Smooth second hand" switch: on means a continuous sweep, off means one step per second.
  • Drift-free (angles always come from the real time) and nothing left running after unmount.
  • An accessible text equivalent of the time.

What a strong answer should cover:

  • The angle formulas: 6 degrees per second, 6 degrees per minute, 30 degrees per hour, each including the fraction of the smaller unit (hour = 30 * (h % 12 + m / 60)).
  • Rotating around the centre with SVG transform="rotate(deg cx cy)" (or CSS transform-origin).
  • requestAnimationFrame for the smooth sweep versus a timeout aimed at the next second for tick mode, switching cleanly with cancellation (cancelAnimationFrame / clearTimeout).
  • Reading the time every frame or tick instead of adding to an angle, so the hands cannot drift.
  • The 360-to-0 wrap at 12 o clock, and why a CSS transition on rotate makes the hand spin backwards there.
  • Rendering cost of 60 updates per second and when to bypass the framework with direct DOM writes.

Clarifying questions expected:

  • "Is a smooth sweep required, or is one tick per second enough?"
  • "SVG or CSS-rotated divs? Should it scale to any size?"
  • "Local time only, or a configurable time zone?"

Code / implementation expected: Yes. A working SVG clock with correct hand angles, both movement modes, a clean switch between them and cleanup.

  • React
  • Canvas
  • Timers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 9 sections

React solution

Every file of the working solution. Open it in the playground to run and change it.

ReactComplete solution
import AnalogClock from "./src/components/AnalogClock";

export default function App() {
  return (
    <main className="page">
      <AnalogClock />
    </main>
  );
}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 54 of 107 in Machine coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Build a Poll / Voting widget

Continue