3

This is a question about JavaScript internals.

Lets say I have 10 async tasks that all take x number of seconds to run. Whilst waiting for a response the script is idle.

In the background the JavaScript engine is asking "Is there anything on the task queue". To my understanding this is a loop. Hence, event loop. I know in Node this is implemented with Libuv. I've read this article which explains a little: https://nikhilm.github.io/uvbook/basics.html

Do JavaScript engines place any restriction on how often this event loop runs in order to balance out performance of the application? Does it run at a set interval?

If I'm off with anything, please correct me. I was purely interested at what interval this event loop runs.

BugHunterUK
  • 8,346
  • 16
  • 65
  • 121
  • 2
    It runs at fast as it can – Jonas Wilms Aug 23 '16 at 19:28
  • if you setTimeout with zero from a function with itself, it fires about 250 times a second in V8. other sources of interruption (eg. ajax) are typically not "pinged" at all, but use lower-level flow controls with sub-ms granularity. – dandavis Aug 23 '16 at 19:34
  • "*restriction on how often this event loop runs in order to balance out performance of the application*" - do you you mean to ask whether they are artificially slowing it down? No, why would they? – Bergi Aug 23 '16 at 19:35
  • @dandavis: That's because `setTimeout` has a minimum timeout of 4ms, not because the event loop is too slow. – Bergi Aug 23 '16 at 19:35
  • 1
    @Bergi: setTimeout (et al) is about the only "js internal" where a granularity applies... – dandavis Aug 23 '16 at 19:41
  • Ah, you meant it as an example of a restriction, not as the frequency of the loop. – Bergi Aug 23 '16 at 19:44
  • See this answer: http://stackoverflow.com/questions/29883525/i-know-that-callback-function-runs-asynchronously-but-why/29885509#29885509 Scroll down a bit to find a low-level description of what the event loop really is – slebetman Aug 24 '16 at 07:31
  • Basically the event loop runs as fast as the OS can respond to interrupts from your network card. Other things like `setTimeout()` etc depends on the granularity of your OS `tick` (it's called `jiffy` on Linux) on some OSes like linux you can actually configure it - lots of real-time embedded systems run Linux on a much faster tick so js timers can run at much finer granularity – slebetman Aug 24 '16 at 07:34
  • 1
    @Bergi according to MDN, if the delay value is 0, the function is executed on the next event cycle. – Celsiuss Dec 01 '20 at 04:52

1 Answers1

2

There is no loop per se in the JavaScript side. There is one in libuv though. Basically libuv will wait until the closest timer hits or an i/o operation happens. Then it will fire a callback in C, which calls the C++ function Node passed and then this triggers JavaScript code to be executed.

Have a look at this presentation, specially the section starting at slide 33.

saghul
  • 1,990
  • 1
  • 13
  • 15