JavaScript - Concurrent mode and Event Loop Event Loop Interpretation

1, Runtime concepts related to the implementation of the concept

JavascriptThere is a based Event Loopconcurrency model event loop;

The following explains a theoretical model to explain the modern browser javascript engine implementation mechanisms and explain some of the semantic description of words;

Visual model represents:

stack stack

Forming a function call stack frame

function foo(b) {
  var a = 10;
  return a + b + 11;
}

function bar(x) {
  var y = 3;
  return foo(x * y);
}

console.log(bar(7)); // 返回 42
复制代码

Brief procedure under the function call:

When invoked bar(7), the establishment of the first stack frameis bar(contains parameters 7and local variables); when the barcall footime, to establish a second stack frameis foo(contains parameters 3* 7and local variables), and placed in barthe 上方, i.e. 栈的顶部the.

When foo(21)finished return 42 when foothe stack frame is removed away, leaving only bar(7); then executed bar, after the return, the entire stack is empty.

Heap Heap

The objects are associated with Heapit, i.e. for indicating a large unstructured memory area.

Queue Queue

A Javascriptuse of a series of messages pending messages queues runtime. Each message is associated with a function to process the message.

In some time of the event cycle 运行时从最先进入队列的消息开始处理队列中的消息. To do so, the message is removed from the queue, the calling function as input parameters associated therewith. As mentioned above, a function always calls for the creation of a stack frame.

Execution of the function which will continue to stackbecome empty. Then the message queue if the next message, then the message queue there is news event loop will execute.

2, Event Loop Event Loop

It is called event loop, because of the way he executed to achieve the following:

while (queue.waitForMessage()) {
  queue.processNextMessage();
}
复制代码

If there is no message, queue.waitForMessage()it will be synchronized waits for the arrival of the message.

Run-to-completion run to the end

After the end of each message is fully implemented, the implementation process to go back the next message.

This provides some excellent characteristics analysis program, including: Whenever you execute a function, will not be preempted, and it would have been fully implemented (and can modify the function of the number of operations) before other code is executed.

The C language and are not the same, for example, if a function runs in one thread, for some time, the system will be executed by the implementation of other code in another thread interrupts.

A disadvantage of this model, when a message would take too long to execute, web users will not be able to deal with some, such as click, srcollinteractivity. A browser will pop up “a script is taking too long to run”this dialog to alleviate this situation. A good solution is to 缩短消息处理的时间,或者把一个消息分割成多个消息.

Adding messages Add a message

In the web browser inside 只要有事件发生并且有监听器绑定的时候,一定会增加一个消息. If there is no listener, the event disappeared. So, with a click on the element and click event handler, it will add a message to the message queue.

setTimeout function takes two parameters: 添加队列的消息and 时间(默认 0 ), this time value represents the message is added to the message queue of the minimum delay time. If the message queue, no other message, this message after a delay time has elapsed, will be processed immediately. If the message queue has other news, setTimeoutthe news must wait until another message to be dealt with to perform. For this reason, the second parameter indicates the 最小的时间间隔while 非确切的时间.

Illustrate, when the expiration time of the second argument, the setTimeout is not executed:

const s = new Date().getSeconds();

setTimeout(function() {
  // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
  console.log("Ran after " + (new Date().getSeconds() - s) + " seconds");
}, 500);

while(true) {
  if(new Date().getSeconds() - s >= 2) {
    console.log("Good, looped for 2 seconds");
    break;
  }
}
复制代码

Zero delays zero delay

Zero delay is not a true representative of the callback function will be executed after 0 milliseconds.

setTimeout zero delay after a given time interval not execute the callback function.

It depends on whether the number of messages in the queue waiting for execution of the task.

for example:

(function() {

  console.log('this is the start');

  setTimeout(function cb() {
    console.log('Callback 1: this is a msg from call back');
  });

  console.log('this is just a message');

  setTimeout(function cb1() {
    console.log('Callback 2: this is a msg from call back');
  }, 0);

  console.log('this is the end');

})();

// "this is the start"
// "this is just a message"
// "this is the end"
// 当前函数 note that function return, which is undefined, happens here 
// "Callback 1: this is a msg from call back"
// "Callback 2: this is a msg from call back"
复制代码

'This is just a message' while after correction, it is output to the correction before printing stage, since the process is only zero delay minimum request delay is not guaranteed a precise time.

In general, setTimeout to wait in the queue after the code executed, will perform all other messages, instant you set specific time intervals.

Reproduced in: https: //juejin.im/post/5cfb7551e51d4510a37babba

Guess you like

Origin blog.csdn.net/weixin_33692284/article/details/91459677