I am creating an app that polls the server for specific changes. I use a self calling function using setTimeout. Something like this basically:
<script type="text/javascript">
someFunction();
function someFunction() {
$.getScript('/some_script');
setTimeout(someFunction, 100000);
}
</script>
In order to make this polling less intensive on the server, I want to have a longer timeout interval; Maybe somewhere within the 1min to 2min range. Is there a point at which the timeout for setTimeout becomes too long and no longer works properly?
I am creating an app that polls the server for specific changes. I use a self calling function using setTimeout. Something like this basically:
<script type="text/javascript">
someFunction();
function someFunction() {
$.getScript('/some_script');
setTimeout(someFunction, 100000);
}
</script>
In order to make this polling less intensive on the server, I want to have a longer timeout interval; Maybe somewhere within the 1min to 2min range. Is there a point at which the timeout for setTimeout becomes too long and no longer works properly?
Share Improve this question asked Sep 10, 2012 at 12:17 flyingarmadilloflyingarmadillo 2,1395 gold badges21 silver badges38 bronze badges 3- I don't think it'd be anywhere near the number you'd be putting in it. – Jeremy Rodi Commented Sep 10, 2012 at 12:18
- 1 Possible duplicate: stackoverflow.com/questions/3468607/… – Richard Commented Sep 10, 2012 at 12:20
- As Richard pointed out, there is a perfect answer to your question, in case you had really large timeouts (larger than ~24 days): stackoverflow.com/questions/3468607/… – Alexis Wilke Commented Jun 29, 2016 at 4:04
2 Answers
Reset to default 15You are technically OK. You can have a timeout of up to 24.8611 days!!! if you really want to. setTimeout can be up to 2147483647 milliseconds (the max for 32 bit integer, and that's about 24 days) but if it is higher than that you will see unexpected behavior. See Why does setTimeout() "break" for large millisecond delay values?
For intervals, like polling, I recommend using setInterval instead of a recursive setTimeout. setInterval does exactly what you want for polling, and you have more control too. Example: To stop the interval at any time, make sure you stored the return value of setInterval, like this:
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!
setTimeout()
uses a 32bit integer for its delay parameter. Therefore the maximum is:
2147483647
Rather than using a recursive setTimeout()
I recommend using setInterval()
:
setInterval(someFunction, 100000);
function someFunction() {
$.getScript('/some_script');
}