Skip to the solution
EasyMachine Coding14 min read

Build a Digital Clock

277 views

The problem

Question presented to candidate: "Build a digital clock widget that shows the current time and updates every second. Users should be able to switch between 24-hour and 12-hour (AM/PM) format. Keep it accurate: if I leave it open for an hour, it should still match my system clock to the second."

Requirements:

  • Show HH:MM:SS, every unit zero-padded, plus the current date.
  • A toggle between 24-hour and 12-hour format (12-hour shows 12 for midnight and noon, never 00, plus AM/PM).
  • The display changes as close to the real second boundary as possible and never drifts.
  • No timers left running after the clock unmounts.

What a strong answer should cover:

  • The source of truth is the system clock: every tick reads new Date() instead of adding 1 to a counter, so a late or skipped tick cannot accumulate as drift.
  • Scheduling: a setTimeout aimed at the next second boundary (1000 - now % 1000) instead of a free-running setInterval(1000) started at an arbitrary millisecond.
  • Cleanup: clearing the timer on unmount, and why React StrictMode in development runs the effect twice (mount, cleanup, mount).
  • Formatting as a pure function (Date + format flag in, strings out): padStart, h % 12 || 12, AM/PM.
  • State model: the format flag is state; the formatted strings are derived, not stored.
  • Accessibility: a semantic <time datetime> element, no aria-live announcing every second, and a toggle button with aria-pressed.

Clarifying questions expected:

  • "Local time only, or should it support other time zones?"
  • "Does it need seconds, or would minute precision be enough (which changes how often it renders)?"
  • "Should the 12/24-hour choice follow the user locale or be a manual toggle?"

Code / implementation expected: Yes. A working component with a self-correcting timer, cleanup, a pure formatting function and the format toggle.

  • React
  • Timers
  • State

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

14 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 DigitalClock from "./src/components/DigitalClock";

export default function App() {
  return (
    <main className="page">
      <DigitalClock />
    </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 22 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 nextEasy

Build a Todo List

Continue