Search code examples
node.jssocket.iosynchronized

Socket.io countdown synchronously?


On my server I call two emits at the same time, which looks like this.

if (songs.length > 0) {
    socket.emit('data loaded', songs);
    socket.broadcast.to(opponent).emit('data loaded', songs);
}

The one is for opponent and the other for himself.

Once the data is loaded a countdown should appear for both players on my android app. For me it is important that they see the same number at the same time on their screen. To be precise it should run synchronized. How can I do this?


Solution

  • As far as js timers are concerned the will be a small amount of difference. We can reduce the difference in time with reduce of latency time, with the difference between the request and response time from the server.

    function syncTime() {
    console.log("syncing time")
    var currentTime = (new Date).getTime();
    
    res.open('HEAD', document.location, false);
    res.onreadystatechange = function()
    {
        var latency = (new Date).getTime() - currentTime;
        var timestring = res.getResponseHeader("DATE");
        systemtime = new Date(timestring);
        systemtime.setMilliseconds(systemtime.getMilliseconds() + (latency / 2))
    };
    res.send(null);
    }
    

    Elapsed time between sending the request and getting back the response need to be calculated, divide that value by 2. That gives you a rough value of latency. If you add that to the time value from the server, you'll be closer to the true server time (The difference will be in microseconds)

    Reference: http://ejohn.org/blog/accuracy-of-javascript-time/

    Hope this helps.