我正在创建一个应用程序,轮询服务器以进行特定更改.我使用setTimeout使用自调用函数.基本上这样的东西:
<script type="text/javascript">
someFunction();
function someFunction() {
$.getScript('/some_script');
setTimeout(someFunction, 100000);
}
</script>
Run Code Online (Sandbox Code Playgroud)
为了使这种轮询在服务器上不那么密集,我希望有一个更长的超时间隔; 也许在1分钟到2分钟的范围内.是否存在setTimeout的超时变得太长且不再正常工作的点?
你在技术上还可以.你可以有超过24.8611天的超时!如果你真的想.setTimeout最高可达2147483647毫秒(32位整数的最大值,大约24天),但如果高于此值,您将看到意外行为.请参阅为什么setTimeout()为大毫秒延迟值"中断"?
对于间隔,如轮询,我建议使用setInterval而不是递归setTimeout.setInterval完全符合你想要的轮询,你也有更多的控制权.示例:要随时停止间隔,请确保存储setInterval的返回值,如下所示:
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!
Run Code Online (Sandbox Code Playgroud)
setTimeout()使用 32 位整数作为其延迟参数。因此最大值为:
2147483647
Run Code Online (Sandbox Code Playgroud)
setTimeout()我建议使用以下方法,而不是使用递归setInterval():
setInterval(someFunction, 100000);
function someFunction() {
$.getScript('/some_script');
}
Run Code Online (Sandbox Code Playgroud)