BACKGROUND
I'm creating an AJAX chat system. It looks something like this:
Mike - hi Jane - 5 minutes ago
Jane - hi Mike - 4 minutes ago
Mike - how's it going - 3 seconds ago
Jane - I'm doing good - 1 second ago
Javascript polls the server every minute and the server responds with 10 of the newest messages. Attached to each message is a Unix timestamp (PHP time()). Javascript is responsible for merging the buffered messages the user currently has with this new server response. The interleaving of messages and accuracy of the "X time ago" message is dependent on how well the Javascript clock is synched with the server clock.
QUESTION
How do you accurately synch the Javascript clock with server clock? Below is what I have so far. I would like to make it more accurate. Currently it does not consider the roundtrip time of the Ajax which does the synching. How do I know the proportion of the roundtrip that is sending, processing, and receiving? Also, how do you deal with users who's clock crystals are just plain busted - for example: it's 7:20 pm GMT but their clock 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;
}
}