JavaScript Operating principle Analysis

Source: Internet
Author: User

Written in the previous words:

found that the use of such a long time of JavaScript, but the operation of its principle is not clear, today deliberately summed up, the great God's theory and his summary are recorded below;

1. What is the JavaScript parsing engine?

In short, the JavaScript parsing engine is a program that can "read" JavaScript code and accurately give the result of the code running. Let's say that when you write var a = 1 + 1 , so a piece of code that the JavaScript engine does is to read (parse) Your code and change the value of a to 2.

People who have learned the principles of compiling know that for static languages (such as Java, C + +, c), called compilers (Compiler) that handle these things, the corresponding dynamic language for JavaScript is called an interpreter (interpreter). The difference between the two is summed up in a nutshell: 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. For example, Firebug's console is a JavaScript interpreter.

However, it is difficult to define now that the JavaScript engine is an interpreter or a compiler, because, for example, like V8 (Chrome JS engine), it in order to improve the performance of JS, before running will be JS compiled into a local machine code (native machines Code), and then to execute the machine code (this speed is much faster), I believe that the JIT (Just in time compilation) must be familiar with it.

I personally think that there is no need to overemphasize what the JavaScript parsing engine really is, and I personally think it is possible to understand what it does. For the compiler or interpreter is how to understand the code, the university to turn out the compilation of teaching materials on it. It is also emphasized that the JavaScript engine itself is a program, and the code is written. For example, V8 is written in C + +.

2. What is the relationship between the JavaScript parsing engine and ECMAScript?

JavaScript engine is a program, we write JavaScript code is also a program, how to let the program read the program? This requires defining the rules. For example, the previously mentioned var a = 1 + 1;it says:

    • The left Var stands for this statement (Declaration), which declares a variable
    • The + on the right indicates the addition of 1 and 1.
    • An equal sign in the middle indicates that this is an assignment statement
    • The final semicolon indicates that the statement is over.

These are the rules, and with that it's a measure of what the JavaScript engine can do to parse JavaScript code based on that standard. So the ECMAScript here is to define these rules. The document, ECMAScript 262, defines a complete set of standards for the language of JavaScript. These include:

    • Var,if,else,break,continue is the key word for JavaScript.
    • Abstract,int,long and so on are javascript reserved words
    • What kind of numbers, what kind of string, etc.
    • Operators (+,-,>,<, etc.) defined
    • Defines the syntax for JavaScript
    • Defines the processing algorithms for criteria such as expressions, statements, and so on, such as how to deal with = =
    • ??

The standard JavaScript engine will be based on this set of documents to achieve, note that the standard is emphasized here, because there are not according to standards, such as the JS engine of IE. That's why JavaScript has compatibility issues. As for why IE JS Engine does not follow the standard to achieve, it is necessary to talk about the browser war, here do not repeat, Google itself.

So, to put it simply, ECMAScript defines the language standard, which the JavaScript engine implements, which is the relationship between the two.

3. What is the relationship between the JavaScript parsing engine and the browser?

Simply put, the JavaScript engine is one of the components of the browser. Because the browser has to do a lot of other things, such as parsing pages, rendering pages, cookie management, history and so on. So, since it is part of the case, JavaScript engines are generally developed by the browser developers themselves. For example: IE9 Chakra, Firefox tracemonkey, Chrome V8 and so on.

It also shows that different browsers use different JavaScript engines. Therefore, we can only say that we want to learn more about which JavaScript engine.

4. Why is JavaScript a single thread?

One of the main features of the JavaScript language is single-threaded, meaning that only one thing can be done at the same time. So why can't javascript have multiple threads? This can improve the efficiency AH.

The single thread of JavaScript is related to its purpose. As a browser scripting language, JavaScript's primary purpose is to interact with the user and manipulate the DOM. This determines that it can only be single-threaded, otherwise it can lead to complex synchronization problems. For example, assuming that JavaScript has two threads at the same time, one thread adds content to one of the DOM nodes, and the other thread deletes the node, which thread should the browser take precedence over?

So, to avoid complexity, JavaScript is a single thread from birth, which has become a core feature of the language and will not change in the future.

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 new standard does not change the nature of JavaScript single threading.

Second, the task queue

A single thread means that all tasks need to be queued, and the previous task is completed before the latter one is executed. If 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 (input) 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.

The designer of the JavaScript language realizes that at this point the main thread can completely ignore the IO device, suspend the waiting task, and first run the task that is in the queue. Wait until the IO device returns the result, and then go back and put the suspended task on hold.

Thus, all tasks can be divided into two types, one synchronization task (synchronous) and one asynchronous task (asynchronous). A synchronization task is a task that is queued on the main thread to perform the latter task only if the previous task is completed, and the asynchronous task refers to a task that goes into the task queue without entering the main thread, and only the task queue notifies the main thread that an asynchronous task can execute. The task will not go into the main thread execution.

Specifically, the operating mechanism for asynchronous execution is as follows. (Synchronous execution is also true because it can be treated as asynchronous execution without an asynchronous task.) )

(1) All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack).

(2) In addition to the main thread, there is a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.

(3) Once all the synchronization tasks in the "execution stack" have been executed, 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.

(4) The main thread constantly repeats the third step above.

III. events and Callback functions

The task queue is a queue of events (which can also be understood as a queue of messages), 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" (callback) 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 "timer" feature mentioned later, the main thread must first check the execution time, and some events will return to the main thread only by the specified time.

Iv. Event Loop

The main thread reads events from the task queue, and the process is cyclic, so the whole mechanism is called event loop.

To get a better understanding of the event Loop, see (quoted from Philip Roberts's speech, "Help, I ' m stuck and an Event-loop").

, when the main thread runs, the heap (heap) and stack (stack) are generated, and the code in the stack calls various external APIs, which include various events (Click,load,done) in the task queue. As soon as the code in the stack finishes executing, the main thread reads the task queue and executes the callback function that corresponds to those events.

The code in the execution stack (the synchronization task) is always executed before the task queue (asynchronous task) is read. Take a look at the example below.

, when the main thread runs, the heap (heap) and stack (stack) are generated, and the code in the stack calls various external APIs, which include various events (Click,load,done) in the task queue. As soon as the code in the stack finishes executing, the main thread reads the task queue and executes the callback function that corresponds to those events.

The code in the execution stack (the synchronization task) is always executed before the task queue (asynchronous task) is read. Take a look at the example below.

    var req=NewXMLHttpRequest(); Req.Open(' GET '.onload = function  ({ }.onerror Span class= "token operator" >= function  () {} .   

The Req.send method in the above code is that the AJAX operation sends data to the server, which is an asynchronous task that means that the system will not read the task queue until all the code for the current script has been executed. Therefore, it is equivalent to the following notation.

    var req=NewXMLHttpRequest(); Req.Open(' GET 'send (.onload = function Span class= "token punctuation" > ({}.onerror = function  ( {} 

That is, specifying the part of the callback function (onload and onerror) does not matter before or after the Send () method, because they are part of the execution stack and the system always executes them before it reads the task queue.

Five, timer

In addition to the events that place an asynchronous task, the task queue can also place timed events that specify how much time some code executes. This is called the timer function, which is the code that executes periodically.

The timer function is mainly by settimeout () and setinterval () These two functions to complete, their internal operation mechanism is exactly the same, the difference is that the former specified code is one-time execution, the latter is repeated execution. The following main discussion settimeout ().

SetTimeout () accepts two parameters, the first is a callback function, and the second is the number of milliseconds to defer execution.

Console.Log(1)settimeout (function< Span class= "token punctuation" > ({consolelog (2) ;} ,1000) ;console. Log (3)               

The result of the above code is 1,3,2, because settimeout () defers the second line to 1000 milliseconds after execution.

If you set the second parameter of settimeout () to 0, the callback function specified immediately (0 millisecond interval) is executed as soon as the current code finishes executing (execution stack emptying).

settimeout ( span class= "token keyword" >function ({console. Log (1) ; }0" ;console.log (2            

The result of the above code is always 2,1, because only after the second line is executed will the system execute the callback function in the task queue.

In summary, setTimeout (fn,0) means that a task is specified to execute at the earliest available idle time of the main thread, that is, to execute as early as possible. It adds an event at the end of the task queue, so it will not be executed until both the synchronization task and the task queue existing events are processed.

The HTML5 standard specifies the minimum value (minimum interval) of the second parameter of the settimeout (), which is not less than 4 milliseconds, and is automatically incremented if it is below this value. Prior to this, the older versions of the browser set the minimum interval to 10 milliseconds. In addition, the changes to those dom, especially those involving page re-rendering, are usually not executed immediately, but once every 16 milliseconds. The effect of using requestanimationframe () is better than settimeout ().

It is important to note that setTimeout () simply inserts the event into the "task queue" and must wait until the current code (execution stack) finishes executing, before the main thread executes the callback function it specifies. If the current code takes a long time, it may take a long time, so there is no guarantee that the callback function will be executed at settimeout ().

Summarize:

Previously just thought that JavaScript is only a simple scripting language, but with the deep after slowly found that JavaScript is still very complex, the knowledge point is quite a lot of, JS implementation principle has been generally understood, but if you want to go deeper, still need more efforts, more reading books, High-performance JavaScript and JavaScript advanced programming are good

JavaScript Operating principle Analysis

Related Article

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.