【问题标题】:Can setTimeout be too long?setTimeout 可以太长吗?
【发布时间】:2012-09-03 07:26:05
【问题描述】:

我正在创建一个应用程序来轮询服务器以获取特定更改。我使用使用 setTimeout 的自调用函数。基本上是这样的:

<script type="text/javascript">
someFunction();

function someFunction() {
  $.getScript('/some_script');
  setTimeout(someFunction, 100000);
}
</script>

为了减少服务器上的轮询强度,我希望有更长的超时间隔;也许在 1 分钟到 2 分钟范围内的某个地方。是否存在 setTimeout 的超时时间过长而无法正常工作的时间点?

【问题讨论】:

标签: javascript


【解决方案1】:

技术上你没问题。如果您真的愿意,最多可以有 24.8611 天!!! 的超时时间。 setTimeout 最长可达 2147483647 毫秒(32 位整数的最大值,大约为 24 天),但如果高于此值,您将看到意外行为。见Why does setTimeout() "break" for large millisecond delay values?

对于间隔,比如轮询,我建议使用 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!

【讨论】:

  • 我不同意 setInterval 而不是递归 setTimeout。 setTimeout 应该在 if 中,以便在需要停止时停止再次调用它。 zetafleet.com/blog/2010/04/…
【解决方案2】:

setTimeout() 使用 32 位整数作为其延迟参数。因此最大值为:

2147483647

我建议使用setInterval(),而不是使用递归setTimeout()

setInterval(someFunction, 100000);

function someFunction() {
   $.getScript('/some_script');
}

【讨论】:

  • 我不同意 setInterval 而不是递归 setTimeout。 setTimeout 应该在 if 中,以便在需要停止时停止再次调用它。 zetafleet.com/blog/2010/04/…
  • 使用递归 setTimeout,您可以确保是否将它放在函数的末尾,以便仅在函数的其余部分已经完成时才调用它。 setInterval 将调用每个间隔,您不可能确保最后一次调用已完成。在某些情况下它很重要,在其他情况下我们不在乎,但我认为意识到这一点是件好事。
猜你喜欢
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 2011-04-26
  • 2013-07-30
相关资源
最近更新 更多