I need to start same task on different tabs/browsers/clients at the same exact time. As close as possible (same second, even millisecond).
What I have right now
-Both clients are sending request to server via AJAX when they start the website.
-Server is taking current timestamp (seconds) and removes it from 10 seconds. Then sends back remaining time to clients.
-Clients receive remaining time, generate timestamp, add remaining time to current time and wait till it is same or greater, then start’s task.
PHP (Server)
<?php
// Remove dot on timestamp
$timeStamp = str_replace('.', '', microtime(true));
// Make it same as JS one (13 symbols)
if (strlen($timeStamp) > 13) {
$timeStamp = substr($timeStamp, 0, -1);
}
// I want last 4 digits - 1st is second, rest 3 are microseconds
$timeStamp = substr($timeStamp, 9, 4);
// Remove time from 10 seconds and we get how many seconds left till start (meaning we start task every 10 seconds on server)
echo 10000 - $timeStamp;
JS (Client)
$.get('ajax.php', function(data){
// Current date
var newDate = new Date().getTime();
// Start date
playDate = newDate + parseInt(data);
// Waiting for current date to be same or greater than start date
while (true){
if (playDate <= new Date().getTime()){
alert('DONE'); // It is pretty close, but not excatly
break;
}
}
});
My question(s)
-Am I going the right way?
-Is this the only way of doing this?
-Can it be done better?
-How can I minimize time difference between different computers/browsers/tabs.
I imagine that I should take into consideration request/response times and do some calculations with them but before I continue I want to make sure that there is no other, better way of achieving my goal and that I’m not going terribly wrong with this solution.
You should use
setTimeout()and not a busy loop like that, and you should adjust your expectations and realize that without complete control of the client machines you can’t expect very close synchronization.Even if you were to measure network latency, that’s not necessarily accurate, as it can change suddenly due to fluctuations in traffic etc.