How can I call a function every 30 seconds on each device at the same time?

I will try to correctly explain my problem. I want to generate a number every 30 seconds, for example:

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

This works well, but not the same on every device, for example, if I open the page with this code, I will get a random number, but if my friend opens it after, for example, there is a delay 5 seconds after opening the page. Is there any way to fix this? I thought something like getting a time server and executing it according to it might work, but I have no idea how to do this.

+5
source share
3 answers

There is no perfect solution to this problem, two options are possible here:
Simple and complex, which should be more accurate.


If you use the same time on all devices *, you can use new Date().getTime() % 30000 for the first call, so they are all synchronized, and then always use the 30000 constant in 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 

* Time intervals will not matter, but seconds are minutes


Another way would be to let the server pass its time, and then guess the delay to fix the load time, and use this instad new Date().getTime()

+1
source

One of the easiest solutions would be to create a new Date object, read the seconds using getSeconds , then round it to a multiple of 30 and schedule the generator in the next step using setTimeout . Once it starts, you can decide to either schedule it again using the same function, or set the interval using setInterval .

If you don't want to rely on a local clock, I think you need to use a service like ntp, but that requires you to know that the delta applies to time, etc.

0
source

You can do this with a single line of PHP.

It works here.

 <script> function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // The variable 'startTime' is synchronized with the server var startTime=parseInt(<?php echo date("now")?>); setInterval(function() { startTime++; if(startTime%30==0) document.write(parseInt(getRandomNumber(0, 14)).toString()+"<br>"); }, 1000); </script> 

Note that I used setInterval instead of setTimeout, so it will be repeated.

0
source

Source: https://habr.com/ru/post/1239274/


All Articles