Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call function every 30 seconds on every devices in the same time?

I am gonna try to explain my problem properly. I want to generate number every 30 seconds, like this :

function getRandomNumber(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
setTimeout(function(){
        getRandomNumber(0,14);
    }, 30000);

This works good, but not same on each device, like if I open the page with this code, I will get random number, but if my friend opens it after e.g. 5 seconds since I have opened the page, there arises delay. Is there any way to fix it? I thought something like getting time server and doing it according to him could work, but I have no idea how to do it.

like image 794
Hugo Avatar asked Nov 08 '22 22:11

Hugo


1 Answers

There is no perfect solution to this problem, here two options:
A simple one and a complicated one wich should be more precise.


If you have the same time on all devices* you could use new Date().getTime() % 30000 for the first call, so they are all on sync, and then always use constant 30000 in the timeout.

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
setTimeout(function() {
  getRandomNumber(0, 14);
}, new Date().getTime() % 30000); // first time use this

* Timezones won't matter, but the seconds of a minute


Another way would to let the server pass his time, and then guess the latency to correct the loading time, and use that instad of new Date().getTime()

like image 157
CoderPi Avatar answered Nov 14 '22 23:11

CoderPi