how many javascript setTimeout/ setInterval call can be set simultaneously in one page?

rabbit picture rabbit · Mar 31, 2010 · Viewed 39.7k times · Source

I have to use atleast 2 setTimeouts and 1 setInterval. Does this have any dependency on the browser or javascript engine being used?

Answer

Seidr picture Seidr · Mar 31, 2010

On a page you can have as many setTimeouts/setIntervals running at once as you wish, however in order to control each individually you will need to assign them to a variable.

var interval_1 = setInterval("callFunc1();",2000);
var interval_2 = setInterval("callFunc2();",1000);
clearInterval(interval_1);

The same code above applies to setTimeout, simply replacing the wording.

As Kevin has stated, JavaScript is indeed single threaded, so while you can have multiple timers ticking at once, only one can fire at any one time - i.e. if you have one that fires a function which 'halts' in execution, for example with an alert box, then that JS must be 'resumed' before another can trigger I believe.

One further example is given below. While the markup is not valid, it shows how timeouts work.

<html>
    <body>
        <script type="text/javascript">
            function addThing(){
                var newEle = document.createElement("div");
                newEle.innerHTML = "Timer1 Tick";
                document.body.appendChild(newEle);
            }   
            var t1= setInterval("addThing();",1000);
            var t2 = setInterval("alert('moo');",2000);
        </script>
    </body>
</html>