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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With