Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 610
rabbit Avatar asked Mar 31 '10 13:03

rabbit


People also ask

Is there a limit to setTimeout?

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.

How many calls can happen at once in JavaScript?

JavaScript is the single-threaded programming language. This means that the JavaScript engine has only one call stack. Therefore, it only can do one thing at a time.

How do you run setInterval 5 times?

“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.

How do I set setTimeout multiple times?

If you need to run a function multiple times, use the setInterval() method. To stop the timeout and prevent the function from executing, use the clearTimeout() method. The JavaScript setTimeout() method returns an ID which can be used in clearTimeout() method.


1 Answers

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.

like image 101
broofa Avatar answered Sep 21 '22 23:09

broofa