7

I've looked around trying to understand how SetInterval but only found how to use it. I already know it's functionality, I'm just curious about how it's able to run something on a separate thread when JS doesn't support threading(at least that's what I read).

I hope I formulated the question properly.

Thanks.

  • 2
    It seems you want to learn about the event loop: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop – Felix Kling Apr 30 '15 at 16:39
  • 1
    There is quite a bit of existing information on this question and variants - see http://stackoverflow.com/questions/2253586 , http://stackoverflow.com/questions/4037738 , http://stackoverflow.com/questions/28650804 , http://stackoverflow.com/questions/1663125 eg. (TLDR: setInterval *might* use threads internally, but it *always* executes the callback code atomically/mutually wrt any other executing JavaScript *in* the same program context: a different page or a WebWorker or establishes a different program context.) – user2864740 Apr 30 '15 at 16:49

1 Answers1

4

setInterval does not run anything on a different thread. It schedules something to run at certain times provided the JS runtime is idle at that time.

You can try out this behavior with something like this:

setInterval(function(){ alert("Hello"); }, 1000);
while (true) { }

The infinite loop will prevent the function from running, because the JS runtime is stuck in the loop.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
  • Correct, but I need a little bit more information on how it "runs at certain times". – José Corretjer-Gómez Apr 30 '15 at 16:52
  • 1
    @JoséCorretjer-Gómez "When no other JavaScript is running". The example above, with the forever-loop, *always* keeps JavaScript in the same program context running so the timer JavaScript callback can never run (even if it is internally triggered). An example of "idle" would be after a page loads and event handlers have been added to elements, but there is no executing JavaScript - only callbacks waiting to fire (including the timeout). – user2864740 Apr 30 '15 at 16:52
  • 1
    What Timothy is referring to is called the Event Loop. This guy gave a real good talk on it: https://www.youtube.com/watch?v=8aGhZQkoFbQ – Edo Apr 30 '15 at 17:32