Timers, games and history · mid
Countdown, stopwatch and timers
A correct timer never counts ticks: it stores when it started and how much time had already passed, computes the display from timestamps, uses the interval only to re-render, survives background-tab throttling, and always clears its interval.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- State: startedAt (or null when paused) and elapsedBefore; display = elapsedBefore + (running ? now − startedAt : 0).
- Pause: elapsedBefore += now − startedAt; startedAt = null. Reset: both to 0/null. Lap: push the current elapsed.
- Countdown: store endAt = now + duration; remaining = max(0, endAt − now); fire 'done' once.
- Why timestamps: Chrome throttles timers in hidden tabs to once per second, and to once per minute after 5 minutes hidden (when silent and chained) — counting ticks drifts badly.
- Re-render with requestAnimationFrame (smooth) or a 100 ms interval; recompute from timestamps on visibilitychange.
- Use performance.now() for elapsed time (monotonic); Date.now() can jump if the clock changes.
- React: clear intervals in effect cleanup; use functional updates or refs to avoid stale closures; one interval, not one per render.
- Format: mm:ss.cs with String(n).padStart(2, '0'). Traffic lights and 'grid lights' (Uber) are timers plus a state sequence — clear pending timeouts when the sequence restarts.
The red pen
Common traps: mistake → fix
Mistake: count++ every 1000 ms
Fix: drifts and freezes in background tabs.
Mistake: setInterval in an effect without cleanup
Fix: intervals multiply.
Mistake: setTime(time + 10) inside the interval with [] deps
Fix: stuck at the first value.
Mistake: Date.now() for stopwatches
Fix: system clock changes break it; prefer performance.now().
Easy to hard
Questions interviewers ask, easy to hard
- Build a stopwatch with start, pause, reset and laps.
- Switch tabs for 5 minutes. Is it still right? Why?
- Build a countdown for an OTP resend button.
- Build a traffic light that cycles red → green → yellow with different durations.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.