Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who or which thread owns the Javascript event loop?

I read many articles here on Javascript event loops. They mainly tell how the event loop works with the Web API or the JS runtime, e.g. moving event from Web API to event queue to be processed, etc. But I do not see any of them explaining where the event loop runs, which really leave me many questions on event loop. For example, who calls the event loop? Is the thread running event loop same as the JS runtime thread which is single-threaded and executing your JS code? Who is the owner of the event loop? Is the event loop running there forever while the Browser windows is open? I understand (not exactly :( ) the event loop kicks in when the main runtime code is completed but how does the event loop kick in? Could somebody help answer my questions to help my understanding of event loop? Thanks!

like image 398
Wei Avatar asked Sep 26 '22 08:09

Wei


1 Answers

who calls the event loop? Who is the owner of the event loop?

The JavaScript Engine (such as V8 in Chrome) hold the event loop. The event loop got its name because of how it's usually implemented, which usually resembles:

while(queue.waitForMessage()){
  queue.processNextMessage();
}

queue.waitForMessage waits synchronously for a message to arrive if there is none currently.

Is the thread running event loop same as the JS runtime thread which is single-threaded and executing your JS code?

JavaScript is single-threaded, there is only one thread in JavaScript runtime (JavaScript engine), which hold the event loop.

Is the event loop running there forever while the Browser windows is open? I understand event loop kicks in when the main runtime code is completed but how does the event loop kick in?

Yes, the event loop is running in the JavaScript engine. Here is one video presented by Philip Roberts to illustrate how event loop working in JavaScript.

Also here is one picture to shown how the following running in JavaScript Engine.

function init() {
  var link = document.getElementById("foo");

  link.addEventListener("click", function changeColor() {
    this.style.color = "burlywood";
  });
}

init();


(source: carbonfive.com)

Source:

http://altitudelabs.com/blog/what-is-the-javascript-event-loop/

http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/

like image 62
zangw Avatar answered Oct 06 '22 01:10

zangw