Syncing a timer across browsers without syncing clocks

Study Room is a small co-working app I've been building: you share a room link, and everyone in the room sees the same Pomodoro timer, who else is online, and a corkboard of sticky notes. No accounts, no install. The timer is the whole point, so it has to agree across every open tab, and it turns out the obvious way to do that is wrong.

The obvious way

My first version had the server own the timer. Every second it decremented secondsLeft and broadcast the new value over a WebSocket to every client in the room. Each browser just displayed whatever number it last received.

This worked on my laptop and fell apart the moment I opened the room on my phone over cellular. Messages arrived in bursts, so the display would freeze for two seconds and then jump. Any dropped frame meant a visibly wrong number. And the server was doing a broadcast per room per second for no real reason, since the information content of "it's now one second later" is zero.

Broadcast the end, not the countdown

The fix was to stop sending state that changes every second and send state that only changes when a human does something. When someone starts a timer, the server records a single value: the Unix timestamp at which it will end. That one number goes out to the room, and the server goes quiet.

Each browser then runs its own local requestAnimationFrame loop and renders endsAt - now. Nothing needs to arrive on time any more. A tab that loses its connection for ten seconds keeps counting down correctly, because it already knows everything it needs.

But whose "now"?

The catch is that Date.now() on the client is not the server's clock. Phones are usually within a second, but I've seen laptops that were off by a minute. If a client computes endsAt - Date.now() with a skewed clock, its timer ends at a different moment from everyone else's, which is exactly the bug I was trying to fix.

So each client measures its offset from the server once on connect, the same way NTP does in miniature:

const t0 = Date.now();
const { serverTime } = await ping();
const t1 = Date.now();
const rtt = t1 - t0;
// Assume the server answered halfway through the round trip.
offset = serverTime - (t0 + rtt / 2);

After that, every "now" on the client is Date.now() + offset. I re-measure every couple of minutes and keep the sample with the smallest round trip, since that one has the least uncertainty about where in the trip the server's timestamp was taken. In practice this keeps clients within a few tens of milliseconds of each other, which is far below anything a person can notice on a 25-minute timer.

What this bought me

The general lesson I took from this is to look at what actually changes. The countdown changes constantly but carries no information. The end time changes rarely and carries all of it. Sending the second thing made the whole system simpler, cheaper, and more correct at once.

Code is on GitHub.