I\'m looking for a way to synchronize time between clients with a good precision (let\'s say 0.5 seconds at least).
I exclude using jsontime or exploiting timestamp
If you just want to sync the timeclock on several computers, NTP themselves recommend setting up your own timeserver.
Set up an api endpoint on your server i.e.
http://localhost:3000/api/time
returns:
status: 200,
body: { time: {{currentTime}} }
How this is done will depend on the backend language that you're using.
Given such an endpoint, this JS snippet I threw together will
var offsets = [];
var counter = 0;
var maxTimes = 10;
var beforeTime = null;
// get average
var mean = function(array) {
var sum = 0;
array.forEach(function (value) {
sum += value;
});
return sum/array.length;
}
var getTimeDiff = function() {
beforeTime = Date.now();
$.ajax('/api/time', {
type: 'GET',
success: function(response) {
var now, timeDiff, serverTime, offset;
counter++;
// Get offset
now = Date.now();
timeDiff = (now-beforeTime)/2;
serverTime = response.data.time-timeDiff;
offset = now-serverTime;
console.log(offset);
// Push to array
offsets.push(offset)
if (counter < maxTimes) {
// Repeat
getTimeDiff();
} else {
var averageOffset = mean(offsets);
console.log("average offset:" + averageOffset);
}
}
});
}
// populate 'offsets' array and return average offsets
getTimeDiff();
You can use this computed offset (just add it to local time), to determine a common "universal" time from each client's context.