Created
December 9, 2012 19:36
-
-
Save skeggse/4246667 to your computer and use it in GitHub Desktop.
ServerTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
socket.on('ping', function(fn) { | |
_.isFunction(fn) && fn(Date.now()); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @constructor | |
* @param {number=} accuracy | |
*/ | |
var ServerTime = function(accuracy) { | |
this.accuracy = accuracy || 5; | |
this.offset = null; | |
this.latency = null; | |
this.oncomplete = null; | |
}; | |
// finds the averaged server's time | |
ServerTime.prototype.sync = function() { | |
var self = this; | |
this.internalSync(/*this.accuracy, */0, 0, 0, function(err, offset, latency) { | |
self.offset = offset; | |
self.latency = latency; | |
_.isFunction(self.oncomplete) && self.oncomplete(); | |
}); | |
}; | |
// test case: server at +2000, client at -2000, rtt is 100 | |
ServerTime.prototype.internalSync = function(/*runs, */total, totalOffset, count, callback) { | |
//if (runs-- <= 0) | |
if (count >= this.accuracy) | |
return callback(null, totalOffset / count, total / count); | |
var start = Date.now(), self = this; // start=-2000 | |
socket.emit('ping', function(time) { // +2050 | |
var end = Date.now(); // end=-1900 | |
var trip = (end - start) / 2; // trip=50 | |
var sTime = time + trip; // +2100 | |
var offset = sTime - end; // offset=4000 | |
self.internalSync(/*runs, */total + trip, totalOffset + offset, count + 1, callback); | |
}); | |
}; | |
// takes the server's time, midrequest, and returns the equivalent time for the client | |
ServerTime.prototype.correct = function(server) { // 2150 | |
if (server.getTime) | |
server = server.getTime(); | |
return server + this.latency - this.offset; // 2200 | |
}; | |
ServerTime.prototype.now = function() { | |
return Date.now() + this.offset; | |
}; | |
ServerTime.prototype.date = function() { | |
return new Date(this.now()); | |
}; | |
var serverTime = new ServerTime(); | |
socket.on('connect', _.bind(serverTime.sync, serverTime)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment