Could setTimeout be too long?

I am creating an application that polls a server for specific changes. I use the self-call function using setTimeout. Something like this basically:

<script type="text/javascript"> someFunction(); function someFunction() { $.getScript('/some_script'); setTimeout(someFunction, 100000); } </script> 

To make this poll less intensive on the server, I want to have a longer timeout interval; Maybe somewhere in the range of 1 to 2 minutes. Is there a moment when the timeout for setTimeout gets too long and no longer works properly?

+4
source share
2 answers

You are technically fine. If you really want this, you can have a waiting time of up to 24.8611 days !!! . setTimeout can reach 2147483647 milliseconds (maximum for a 32-bit integer and about 24 days), but if it is higher, you will see unexpected behavior. See Why setTimeout () "break" for large delay values ​​in milliseconds?

For intervals, such as polling, I recommend using setInterval instead of the recursive setTimeout. setInterval does exactly what you want for the survey, and you have more control. Example. To stop the interval at any time, be sure to keep the return value of setInterval, for example:

 var guid = setInterval(function(){console.log("running");},1000) ; //Your console will output "running" every second after above command! clearInterval(guid) //calling the above will stop the interval; no more console.logs! 
+5
source

setTimeout() uses a 32-bit integer for the delay parameter. Therefore, the maximum:

 2147483647 

Instead of using recursive setTimeout() I recommend using setInterval() :

 setInterval(someFunction, 100000); function someFunction() { $.getScript('/some_script'); } 
+2
source

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


All Articles