views:

272

answers:

3

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

+2  A: 

You can use as many as you want. Just remember that JavaScript is single threaded, so none of them can execute in parallel.

Kevin
+1  A: 

On a page you can have as many setTimeouts/setIntervals running at once, 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 fuction 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>
Seidr
+1  A: 
var interval_1 = setInterval("callFunc1();",2000);

calls eval() which is evil so it's BAD. Use that instead : var interval_1 = setInterval(callFunc1,2000); And for the qustion, you may use as many as you want but if all have the same interval between two action, you better do it that way : var interval = setInterval(function() { fct1(); fct2(); },2000);

xavierm02