I have to use atleast 2 setTimeouts and 1 setInterval. Does this have any dependency on the browser or javascript engine being used?
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.
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.
“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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With