javascript setTimeout 有什么限制吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12168708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any limit to setTimeout?
提问by Mahn
Specifically talking about (server side) V8, and assuming I'm not concerned about accuracy because I can detect and compensate for it, could I literallyset up thousands of relatively simple timeouts several seconds apart from each other using setTimeout without facing any other limit other than RAM? Is there any catch I should be aware of if I were to use a system where there may be thousands of scheduled timeouts at any given time?
具体讲(服务器端)V8,并假设我不关心的准确性,因为我可以检测并对其进行补偿,可我从字面上设立上千个相对简单的超时几秒钟彼此分开使用的setTimeout没有遇到任何其他限制除了内存?如果我要使用在任何给定时间可能有数千个预定超时的系统,我应该注意什么?
For the record I've read John's Resig excellent article on How Javascript Timers workso no need to point out anything that's already covered there :) I'm aware node.js is single threaded, timers can block other timers if they take too long, etc.
作为记录,我已经阅读了 John's Resig 关于Javascript 计时器如何工作的优秀文章,因此无需指出那里已经涵盖的任何内容:) 我知道 node.js 是单线程的,如果计时器花费太长时间,它们可能会阻塞其他计时器, 等等。
PS: I'm strictly trying to understand how viable is what I describe, no need to point out "there's surely a better way to do what you intend to do!".
PS:我严格地试图理解我所描述的内容有多可行,无需指出“肯定有更好的方法来做你想做的事!”。
回答by Sam Shiles
The only real world limit you may come up against is the amount of memory available to node. Use the following code to test. I successfully ran the example below using oneMillion and int32Max. When using int64Max, I received the following error from node. I'm using 64bit windows with 4gb of RAM.
您可能遇到的唯一现实世界限制是节点可用的内存量。使用以下代码进行测试。我使用 oneMillion 和 int32Max 成功运行了下面的示例。使用 int64Max 时,我从节点收到以下错误。我正在使用带有 4GB RAM 的 64 位 Windows。
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
Node code to test:
要测试的节点代码:
var util = require('util');
var int64Max = 9007199254740992;
var int32Max = 2147483647;
var oneMillion = 1000000;
var tenThousand = 10000;
var counter = 0;
//Exchange the limiter with one of the above vars to test.
for (var i = 0; i < oneMillion; i++){
setTimeout(log, 1);
//Required as the timeout/callback method will not be called until the loop ends due
//to node/js being single threaded.
util.log('loop:' + i);
}
function log(){
util.log('callback: ' + counter++);
}
回答by Jeremy J Starcher
I don't know how node operates, but if you create MAXINT+1 timers without letting them run, you risk an integer overflow.
我不知道节点是如何运行的,但是如果您创建 MAXINT+1 计时器而不让它们运行,则会冒整数溢出的风险。