30

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

rabbit
  • 301
  • 1
  • 3
  • 3

4 Answers4

32

tl;dr: Don't worry about the cost of timers until you're creating 100K's of them.

I just did a quick test of timer performance by creating this test file (creates 100K timers over and over):

<script>
var n = 0; // Counter used to verify all timers fire

function makeTimers() {
  var start = Date.now();
  for (var i = 0; i < 100000; i++, n++) {
    setTimeout(hello, 5000);
  }
  console.log('Timers made in', Date.now() - start, 'msecs');
}

function hello() {
  if (--n == 0) {
    console.log('All timers fired');
    makeTimers(); // Do it again!
  }
}

setTimeout(makeTimers, 10000);  // Wait a bit before starting test
</script>

I opened this file in Google Chrome (v54) on my circa ~2014 Macbook Pro, and went to the Timeline tab in Developer Tools and recorded the memory profile as the page loaded and ran thru 3-4 cycles of the test.

Observations

The timer creation loop takes 200ms. The page heap size starts at 3.5MB pre-test, and levels out at 3.9MB.

Conclusion

Each timer takes ~.002 msecs to set up, and adds about 35 bytes to the JS heap.

broofa
  • 37,461
  • 11
  • 73
  • 73
  • 1
    This is very impressive, I expected a much larger overhead. I was worried that 100-200 timers at once would be overkill. – byxor Dec 14 '18 at 16:29
26

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>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Seidr
  • 4,946
  • 3
  • 27
  • 39
  • 1
    nice explanation, finally I understood how things are with setTimeout...i thought that only 1 can run at a time, this was due to the fact that I tested it using alert commands, which are, of course, an exception in this case – Fazi Jul 16 '12 at 11:30
13

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

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
7

var interval_1 = setInterval("callFunc1();",2000); calls eval() which is evil so it's BAD. Use this instead var interval_1 = setInterval(callFunc1,2000);

And for the question, you may use as many as you want but if all have the same interval between two actions, you better do it this way

var interval = setInterval(function() {
  // function1
  fct1(); 
  // function2
  fct2();
 },2000);
brent_white
  • 1,009
  • 1
  • 13
  • 26
xavierm02
  • 8,457
  • 1
  • 20
  • 24
  • 1
    Why eval() is devil and BAD? – Lazy Aug 18 '15 at 18:02
  • @Lazy: It prevents most optimizations and is therefore far slower than the alternative. – xavierm02 Aug 19 '15 at 09:34
  • `eval` is neither evil or bad. Passing a string to `setTimeout` for evaluation instead of a callback _is_. – John Weisz Sep 12 '16 at 12:45
  • @JohnWhite Ok, let me rephrase that. "Unless you want to execute code that directly depends on the input, then using `eval` is probably making your code slower and less readable for no good reason. Most (all?) of the time, if you want to use `eval`, it's because you haven't understood what you're trying to do and/or JavaScript well enough." So `eval` *is* evil (which doesn't imply useless, it's just really tempting to use it but you shouldn't unless you really have to) and this use case of `eval` *is* bad because it can easily be rewritten without eval. – xavierm02 Sep 12 '16 at 15:31