Javascript clock synchronization with server clock

BACKGROUND

I am creating an AJAX chat system. It looks something like this:

Mike - hi Jane - 5 minutes ago

Jane - Hi Mike - 4 minutes ago

Mike - how it happens - 3 seconds ago

Jane - I'm doing well - 1 second ago

Javascript checks the server every minute, and the server responds with 10 new messages. A Unix timestamp is attached to each message (PHP time ()). Javascript is responsible for combining the buffered messages that the user has with this new server response. Message rotation and the accuracy of the “X time ago” message depend on how well the Javascript clock synchronizes with the server clock.


Question

How do you precisely synchronize Javascript clocks with server clocks? Below I am still. I would like to make it more accurate. It currently does not take into account the Ajax rounding time that synchronizes. How to find out the share of sending, processing and receiving mail? In addition, how do you feel about users whose crystal watches are simply busted - for example: it's 7:20 PM GMT, but their watch actually says 7:15 PM GMT?

Clock = {
   serverOffset = 0;

   synch: function() {
      new Ajax.Request(
         '/getServerTime.php', {
            onSuccess: function(transport) {
               this.serverOffset = parseInt(transport.responseText) - 
                  new Date().getTime() / 1000;
            }
         }
      );
   },

   getServerTime: function(myTime) {
      if (typeof(myTime) === 'undefined') {
         myTime = new Date().getTime() / 1000;
      }
      return myTime + this.serverOffset;
   },

   serverToMyTime: function(serverTime) {
      return serverTime - this.serverOffset;
   }
}
+3
source share
3 answers

, , - , , . , , , , , .

, , , . , [start, end] .

+3

. , . , . , , , . . , , , - .

+3

flash . 100% . , flash 1 , .

, 100% .

FMS, .

javascript, .

maybe html5 will solve this problem with socket speeds soon

+1
source

Source: https://habr.com/ru/post/1776808/


All Articles