3

If I did something like

setInterval(setInterval(function(){console.log("Interval hit");}, 1000), 100);

then what would happen? I want to understand what would happen from a deep level of Javascript, browsers, dates/times, etc.

Depak Chopra
  • 307
  • 2
  • 6

1 Answers1

3

The code as you have it would only create one interval timer (the inner one) firing once a second and outputting to the console. For the outer setInterval() call, you are passing the timerID to the outer one instead of a function reference so no outer interval will be created, thus this code will just create one interval timer.

If what you meant to ask was about something evil like this:

setInterval(function() {
   setInterval(function(){
        console.log("Interval hit");
   }, 1000);
}, 100);

Then, that would create an exponentially larger number of interval timers as each 100ms, it would create another interval timer. This would eventually exhaust some sort of system resource and how exactly it would fail would likely vary depending upon implementation.

When you have too many timers trying to fire at the same time, then Javascript will just be "late" in firing timers. Because it is single threaded, it has to wait for a previous timer that is executing before it can fire the next one. This answer about async Ajax events explains a fair amount about the Javascript event queue (which also applies to timers) so it may help you understand timers too:

How does JavaScript handle AJAX responses in the background?

Timer events go into the event queue and the next one is serviced in order when the currently running JS thread of execution finishes. Creating too many timers will just put more things in the event queue than can be serviced, resulting in the event queue growing out of control either until it exhausts some resource limit or until it hits some internal browser limit (depending upon implementation).

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979