JavaScript Internals: At what interval does the event loop run?
Asked Answered
M

1

4

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.

Monies answered 23/8, 2016 at 19:24 Comment(9)
It runs at fast as it canBorglum
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.Virge
"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?Lookeron
@dandavis: That's because setTimeout has a minimum timeout of 4ms, not because the event loop is too slow.Lookeron
@Bergi: setTimeout (et al) is about the only "js internal" where a granularity applies...Virge
Ah, you meant it as an example of a restriction, not as the frequency of the loop.Lookeron
See this answer: #29884025 Scroll down a bit to find a low-level description of what the event loop really isPd
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 granularityPd
@Lookeron according to MDN, if the delay value is 0, the function is executed on the next event cycle.Yttriferous
H
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.

Homing answered 24/8, 2016 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.