How I built a stopwatch that survives sleep

macOS sleep breaks timers. I fixed Kronometre by storing an instant instead of a counter.

The problem

When I started Kronometre I took the classic route: store a start time, compute the difference from Date() on every tick. It worked fine on my desk. Then I closed the lid.

When the Mac woke up the counter was either behind or ahead. The reason is simple: timers pause during sleep, and I was accumulating tick counts. No matter how long the machine slept, the total was always wrong.

The fix: store an instant, not a counter

The fix was to stop counting. When the app launches I store a single Date instant, and the displayed elapsed time is computed against it every frame:

final class StopwatchStore {
    private let startedAt: Date
    private var accumulated: TimeInterval = 0
    private var pausedAt: Date?

    var elapsed: TimeInterval {
        accumulated + (pausedAt == nil ? Date().timeIntervalSince(startedAt) : 0)
    }
}

That single idea solved everything. The timer no longer carries the elapsed time; it only refreshes the screen. Whatever happens during sleep, elapsed comes back correct on wake because the real source is the system clock.

Listening for sleep

The second piece is correcting the display immediately on wake. macOS gives us notifications for exactly this:

NSWorkspace.shared.notificationCenter.addObserver(
    self, selector: #selector(didWake),
    name: NSWorkspace.didWakeNotification, object: nil)

@objc private func didWake() { render(elapsed: store.elapsed) }

The same notification arrives whether the app is backgrounded or frontmost, so the menu-bar label never shows a stale value.

The result

Kronometre today is about 110 KB with zero dependencies. It stays second-accurate even after days of sleep. The lesson I keep: compute from the source instead of accumulating state.

Don't count time. Ask the clock.