Search code examples
javascripttimerreal-timeepochntp

Realtime clock synch across browser clients


I am writing a collaborative music web-app that can be "played" in parallel across browsers in different devices. Imagine two people standing in the same room, and playing their "instruments" together. Each one holding a different device running a webapp in their hands.

I need both devices to have a synched timer where they agree on what time it is +/- several milliseconds.

My first attempt was simply to trust that my 2 devices (windows PC, and android phone) are synched. But they have several seconds between their clocks. So I realize that I need to implement this myself.

Is there a REST/Websocket service that I can use to periodically synchornize the apps' time? If not, is there a standard algorithm that would be effective to implement over websocket?

My naiive instinct is to implement a 4 way ping between the client and server, and half their ping/pong time, but I am pretty sure that someone has allready implemented something better.

As we are talking about music, standard multiplayer time-drifts won't cut it. I need the clocks to be in synch in greater accuracy than network ping time.

Is there something like NTP that works in a browser?


Solution

  • This works mostly ok for now. Some hicups if browser execution is delayed on busy machine.

    I echo the requests back to the client with the addition of servertime from the server.

        function syncTime(requestTimeMs, serverTimeMs) {
            var now = Date.now();
            var latency = (now - requestTimeMs) / 2;
            var serverTimeWithLatency = serverTimeMs + latency;
            timeOffsetFromServer = parseInt(serverTimeWithLatency - now);
        }
    
        function getSynchedTimeMs() {
            return Date.now() + timeOffsetFromServer
        }