2
votes

I am building a chat app currently with PubNub. The problem now is from the app/frontend point of view, how should it get the time (server time). If every message is sent to the server, I could get the server time there. But with a 3rd party service like PubNub, how can I manage this? Since app sends messages to PubNub rather than my server. I dont want to rely on local time as users might have inaccurate clocks.

The simplest solution I thought of is: When app starts up, get server time. Record the difference between local time and server time (diff = Date.now() - serverTime). When sending messages, the time will be Date.now() - diff. Is this correct so far?

I guess this solution assumes 0 transmission (or latency) time? Is there a more correct or recommended way to implement this?

1
What is the purpose of the time? - Ricardo Stuven
@RicardoStuven its to record when was the message sent - Jiew Meng
Sent from where to use it or store it where? (client, server?) - Ricardo Stuven

1 Answers

2
votes

Your use case is probably the reason why pubnub.time() exists.

In fact, they even have a code example describing your drift calculation.

https://github.com/pubnub/javascript/blob/1fa0b48227625f92de9460338c222152c853abda/examples/time-drift-detla-detection/drift-delta-detection.html

// Drift Functions
function now(){ return+new Date }
function clock_drift(cb) {
    clock_drift.start = now();
    PUBNUB.time(function(timetoken){
        var latency     = (now() - clock_drift.start) / 2
        ,   server_time = (timetoken / 10000) + latency
        ,   local_time  = now()
        ,   drift       = local_time - server_time;
        cb(drift);
    });
    if (clock_drift.ival) return;
    clock_drift.ival = setInterval( function(){clock_drift(cb)}, 1000 );
}
// This is how you use the code
// Periodically Get Latency in Miliseconds
clock_drift(function(latency){
    var out = PUBNUB.$('latency');
    out.innerHTML = "Clock Drift Delta: " + latency + "ms";
    // Flash Update
    PUBNUB.css( out, { background : latency > 2000 ? '#f32' : '#5b5' } );
    setTimeout( function() {
        PUBNUB.css( out, { background : '#444' } );
    }, 300 );
});