gpt4 book ai didi

javascript - setTimeout 可以太长吗?

转载 作者:数据小太阳 更新时间:2023-10-29 05:13:14 24 4
gpt4 key购买 nike

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

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

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

为了让这个轮询在服务器上不那么密集,我想有一个更长的超时间隔;也许在 1 分钟到 2 分钟范围内的某个地方。是否存在 setTimeout 的超时时间过长而无法正常工作的情况?

最佳答案

你在技术上没问题。如果您确实愿意,您可以设置最长 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!

关于javascript - setTimeout 可以太长吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12351521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com