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
12for midnight and noon, never00, 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
setTimeoutaimed at the next second boundary (1000 - now % 1000) instead of a free-runningsetInterval(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, noaria-liveannouncing every second, and a toggle button witharia-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.