Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - Is there any limit to setTimeout?

Specifically talking about (server side) V8, and assuming I'm not concerned about accuracy because I can detect and compensate for it, could I literally set 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?

For the record I've read John's Resig excellent article on How Javascript Timers work so 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.

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!".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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++);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...