this._window=10;// The window size for the sliding average of offset samples.this._minWindow=4;// The window size for the sliding average of offset samples.this._offsets=newArray(); // The samples used to calculate the average offset.this.offset=0; // The offset in ms between the clients clock and the servers clock. Add this to the local// time epoch to obtain server time.this.samples=0; // The number of samples used to calculate the offset. If 0, the offset is not valid.this.getServerTime=function(){// return: long// Summary:// Calculate the current time on the server// returnnew Date().getTime()+this.offset;
}this.getServerDate=function(){// return: Date// Summary:// Calculate the current time on the server// returnnew Date(this.getServerTime());
}this.setTimeout=function(/*function*/call,/*long|Date*/atTimeOrDate){// Summary:// Set a timeout function relative to server time// call:// the function to call when the timeout occurs// atTimeOrTime: // a long timestamp or a Date representing the server time at// which the timeout should occur.var ts=(atTimeOrDate instanceof Date)?atTimeOrDate.getTime():(0+atTimeOrDate);
var tc=ts-this.offset;
var interval=tc-new Date().getTime();
if(interval<=0)
interval=1;
return setTimeout(call,interval);
}this._in=function(/*Object*/msg){// Summary:// Handle incoming messages for the timesync extension.// description:// Look for ext:{timesync:{}} field and calculate offset if present.// msg: // The incoming bayeux messagevar channel=msg.channel;
if(channel && channel.indexOf('/meta/')==0){if(msg.ext&& msg.ext.timesync){var sync=msg.ext.timesync;
var now=new Date().getTime();
this._offsets.push(sync.ts-sync.tc-(now-sync.tc-sync.p)/2);
if(this._offsets.length>this._window)this._offsets.shift();
this.samples++;
var total=0;
for(var i inthis._offsets)
total+=this._offsets[i];
this.offset=parseInt((total/this._offsets.length).toFixed());
if(this.samples<this._minWindow)
setTimeout(dojox._scopeName + ".cometd.publish('/meta/ping',null)",100);
}}return msg;
}this._out=function(msg){// Summary:// Handle outgoing messages for the timesync extension.// description:// Look for handshake and connect messages and add the ext:{timesync:{}} fields// msg: // The outgoing bayeux messagevar channel=msg.channel;
if(channel && channel.indexOf('/meta/')==0){var now=new Date().getTime();
if(!msg.ext)
msg.ext={};
msg.ext.timesync={tc: now};
}return msg;
}