The execution mechanism of JS engine

Source: Internet
Author: User

JS engine execution mechanism 1. What is the JavaScript parsing engine
    • The JS engine is a program that can read JavaScript code and accurately give the result of the code running.
    • For static languages (Eg:java, C + +, c), the compiler that handles these things is called an interpreter for dynamic languages such as JavaScript. The difference: The compiler compiles the source code into another code (such as machine code or bytecode), and the interpreter directly parses and outputs the result of the code, such as the Firebug console is a JavaScript interpreter.
    • V8 engine, in order to improve the performance of JS, before running will be JS compiled into a local machine code, and then to execute machine code. The bottom layer is written in C + +.
2. Operating mechanism:
    • First of all, to determine whether JS is synchronous or asynchronous, synchronization into the main process, asynchronous into the event table
    • An asynchronous task registers a function in the event table and is pushed into the event queue when the trigger condition is met
    • The synchronization task enters the main thread and continues until the main thread is idle, and then goes to the event queue to see if there is an executable asynchronous task, which is pushed into the main process.

MACRO-TASK (Macro Task): Includes whole code script, SetTimeout, setinterval
Micro-task (Micro Task): Promise, Process.nexttick

Perform a macro task that, if it encounters a micro-task, puts it into the "event queue" of the micro-task;
After the current macro task executes, it will look at the "event queue" of the micro-task and execute all the micro tasks in turn.

setTimeout(function(){console.log("定时器开始啦")});new Promise(function(resolve){    console.log("马上开始");    for(var i=0;i<1000;i++){i==99 && resolve();}}).then(function(){console.log("执行then函数")});console.log("代码执行完毕");

Analysis:

    • First perform the macro task under script, encounter SetTimeout, and put it in the "asynchronous queue" Li of the macro task
    • Encounter new promise direct execution, print "Execute for loop Now"
    • Encountered then method, is a micro task, put it into the "Micro task queue"
    • Print "End of code Execution"
    • The macro task is completed, view the micro-task, found a then method in the function, print "Execute then function"
    • After the synchronization task in the main process completes, look at the asynchronous queue, execute Console.log ("timer started");
3. About SetTimeout
setTimeout(function(){console.log(‘执行了‘);});

After 3s, the function in SetTimeout is pushed into the event queue, and the task in the event queues is only executed when the main thread is idle. Therefore, only the same time (1) 3s (2) The main thread is idle, only 3s after the function is executed.

4. A single thread for JavaScript

To take advantage of the computational power of multicore CPUs, HTML5 proposes a web worker standard that allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not manipulate the DOM. So, this standard does not change the nature of JavaScript single threading.

5. About the task queue
    • Because a single thread, all tasks need to be queued, the previous task takes a long time, the latter task has to wait.
    • If the queue is because of large computational capacity, the CPU is not busy, but also forget, but many times the CPU is idle, because the IO device is very slow (such as the Ajax operation from the network to read data), have to wait for the results, and then down to execute.
    • At this point, the main thread can completely ignore the IO device, suspend the task in wait, line run the task in the back. Wait until the IO device returns the result, and then go back and put the suspended task on hold.
    • Thus: The task is divided into two types, synchronous and asynchronous. Synchronous task: A task that is queued on the main thread to perform the latter task before it can be executed; asynchronous task: Instead of entering the main thread, it is a task that goes into the task queue, and only the task queue notifies the main thread that an asynchronous task can be executed. The task will not go into the main thread execution.
6. Asynchronous execution mechanism
    • All synchronization tasks are performed on the main thread to form an execution stack;
    • In addition to the main thread, there is also a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue;
    • Once all the synchronization tasks in the execution stack have been completed, the system reads the task queue to see what events are in it. Those corresponding asynchronous tasks, so end the wait state, go to the execution stack, and start execution.
    • The main thread continually repeats the third step above.
    • As long as the main line Cheng, will read "task queue", this is the operation mechanism of JavaScript.
7. Events and Callback functions
    • The task queue is the queue for an event, and the IO device completes a task by adding an event in the task queue that indicates that the associated asynchronous task can enter the execution stack. The main thread reads the "Task queue", which is what events are read inside.
    • Events in the task queue, in addition to the IO device events, include some user-generated events (such as mouse clicks, page scrolling, and so on). Whenever a callback function is specified, these events go into the task queue and wait for the main thread to read.
    • The so-called "callback function" is the code that will be hung up by the main thread. An asynchronous task must specify a callback function that executes the corresponding callback function when the main thread starts executing an asynchronous task.
    • A "task queue" is a FIFO data structure, preceded by events, that are first read by the main thread. The main thread of the read process is basically automatic, as long as the execution stack is emptied, the first event on the "task queue" automatically enters the main thread. However, due to the existence of a "timer" function, the main thread must first check the execution time, some events only to the specified time, to return to the main thread.
8.node.js's EventLoop
    • V8 Engine parsing JavaScript script
    • Parse the code, call the node API
    • The LIBUV Library is responsible for node API execution. It assigns different tasks to different threads, forms an event loop, and asynchronously returns the execution results of the task to the V8 engine.
    • The V8 engine then returns the result to the user.
      In addition to the two methods of settimeout and SetInterval, node. JS also provides: Process.nexttick and setimmediate.
      Process.nexttick can then trigger the callback function before the current "execution stack" tail-the next event Loop (the main thread reads the "Task queue"). That is, it specifies that the task always occurs before all asynchronous tasks.
      Setimmediate adds an event at the end of the current task queue, and the task it specifies is always executed at the next event loop.

Reference:
10-minute understanding of the JS engine execution mechanism 1190000012806637
A detailed explanation of JavaScript running mechanism: Another talk about event Loop http://www.ruanyifeng.com/blog/2014/10/event-loop.html

The execution mechanism of JS engine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.