Skip to the solution
MediumFrontendAsked in 20247 min read

Build a Drift-Corrected Interval Clock (setInterval Alone Drifts Over Time)

1.1k views

The problem

Problem, as an interviewer would state it: "setInterval(fn, 1000) is not actually guaranteed to fire exactly every 1000ms — explain why, and implement a version that stays accurate over a long-running session."

Examples:

Code
const clock = createDriftCorrectedInterval(tick, 1000);
// stays close to real wall-clock 1000ms boundaries even if tick() itself
// occasionally takes 20-30ms to run, unlike plain setInterval

Clarifying questions expected:

  • Is the drift caused by the EVENT LOOP being busy, or specifically by the handler's OWN execution time?
  • Does "accurate" mean each individual gap is exactly wait, or that the TOTAL elapsed time after N ticks matches N × wait?
  • Is pausing/resuming (e.g., a background browser tab) in scope, or just steady-state drift?

Code / implementation expected: Yes — real, direct, measured proof comparing accumulated drift between a naive setInterval and a corrected version under identical conditions.

  • js-coding
  • utility
  • algorithm

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

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, measured proof: a drift-corrected interval accumulates far less lag than plain setInterval under an identical slow handler, over 15 real ticks

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 85 of 154 in JavaScript coding

Keep your momentum going.

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

Up nextMedium

Implement Array.prototype.includes() Handling NaN Correctly

Continue