drclue wrote:
[...]
There are a limited number of timers , so
if you use them all up , setTimeout() and setInterval() would
return null in lue of timer id's and do nothing.
What is the limit that you have discovered? There's no limit noted in
either Gecko or MSDN documentation. I tested setting concurrent
timeouts[1] in Firefox and IE - Firefox was happy up to 100,000[2] (and
probably beyond, my patience ran out), IE seems to get lost somewhere
between 60,000 and 70,000. You can set a much higher number
consecutively without any problems - both browsers were happy to set
500,000 consecutive timeouts in blocks of 10,000 set concurrently.
Firefox seems to allocate timer numbers sequentially from 1, IE uses
some other scheme that numbers timeouts around 2.7e7. There is a
simple test below - it will consume quite a bit CPU when running. You
can watch the memory use climb as more timers are set, then see it fall
as they are executed.
If you are setting in excess of say 10,000 timers concurrently there is
something seriously wrong with your application architecture (which is
probably true if you are setting more than about 10 concurrently). And
if you are setting more than 500,000 consecutively, you're probably
expecting to set one every few seconds over several weeks in which case
you need to look seriously at memory management (and whether JavaScript
is the right tool for the job).
<script type="text/javascript">
function emptyFn() {};
var lotsTimer, numRuns = 0;
function setLotsOfTimers( limit ){
++numRuns;
setTimers(limit);
lotsTimer = setTimeout('setLotsOfTimers(' + limit + ');',20000);
}
function setTimers( limit ){
msgString = 'Reached limit: ' + limit;
var msgEl = document.getElementById('xx');
while ( limit-- ){
var x = setTimeout('emptyFn();', 100);
if ('number' != typeof x){
msgEl.innerHTML = 'Didn\'t finish.<br>Last setTimeout: '
+ x + '<br>Runs: ' + numRuns;
if (lotsTimer) clearTimeout(lotsTimer);
return;
}
}
msgEl.innerHTML = msgString + '<br>Last setTimeout: '
+ x + '<br>Runs: ' + numRuns;
}
</script>
<form action="">
<input type="text" name="limit" value="10000">
<input type="button" value="Set timers"
onclick="setTimers( this.form.limit.value );">
<input type="button" value="Set lots..."
onclick="setLotsOfTimers(this.form.limit.value);">
<input type="button" value="Cancel lots"
onclick="if (lotsTimer){clearTimeout(lotsTimer);lotsTimer=null;">
</form>
<div id="xx"></div>
1. "Concurrent" meaning all set within a loop so that all of them are
set before the first one runs
2. I think setting 100,000 concurrent timeouts in a javascript
application is absurd, it was done here purely to see if I could find a
limit. I think the practical limit is probably about 1,000 or less.