original text :1.http://blog.csdn.net/liaodehong/article/details/50488098

2.Stack Three meanings  ( Ruan Yifeng )

3. http://lib.csdn.net/base/javascript

The main thread is from " Task queue " Read events in , The process is cyclical , So the whole operation mechanism is also called Event Loop( The event loop ).

Above picture , When the main thread is running , Make a pile (heap) And the stack (stack), The code in the stack calls all kinds of external API, They are " Task queue " Add all kinds of events (click,load,done). As long as the code in the stack is executed , The main thread will read " Task queue ", Execute the callback function corresponding to those events in turn .

Execute the code in the stack ( Synchronization task ), Always reading " Task queue "( Asynchronous task ) Before execution . Please see the following example .

 var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function (){};
req.onerror = function (){};
req.send();

In the above code req.send The method is Ajax Operation to send data to the server , It's an asynchronous task , It means that only all the code of the current script is executed , The system will read " Task queue ". therefore , It is equivalent to the following .

 var req = new XMLHttpRequest();
req.open('GET', url);
req.send();
req.onload = function (){};
req.onerror = function (){};

in other words , Specifies the part of the callback function (onload and onerror), stay send() The front or back of the method doesn't matter , Because they are part of the execution stack , The system always executes them , To read " Task queue ".

So called task queue :

3、 ... and 、 Events and callback functions

" Task queue " It's a queue of events ( It can also be understood as a queue of messages ),IO The device accomplishes a task , It's just " Task queue " Add an event to , Indicates that related asynchronous tasks can enter " Execution stack " 了 . Main thread read " Task queue ", Is to read the events in it .

" Task queue " In the event , except IO Beyond the event of the device , It also includes some user generated events ( For example, mouse click 、 Page scrolling and so on ). As long as the callback function is specified , When these things happen, they go into " Task queue ", Wait for the main thread to read .

So-called " Callback function "(callback), It's the code that will be hung by the main thread . Asynchronous tasks must specify callback functions , When the main thread starts executing asynchronous tasks , Is to execute the corresponding callback function .

" Task queue " It's a first in, first out data structure , The events at the front , Priority read by main thread . The reading process of the main thread is basically automatic , As soon as the stack is emptied ," Task queue " The first event on the thread automatically enters the main thread . however , Due to the existence of " Timer " function , The main thread first checks the execution time , Some events only arrive at the appointed time , To return to the main thread .

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Let me write it out front :

It's been used for such a long time JavaScript, But its operation principle is not clear , To sum up today , Record the theory of the great gods and their own summary below ;

1. What is? JavaScript Parsing engine ?

In short ,JavaScript The parsing engine is able to “ Read ”JavaScript Code , And accurately give the results of the code run a program . For example , When you write  var a = 1 + 1;  Such a piece of code ,JavaScript What the engine does is to understand ( analysis ) Your code , And will a The value of a 2.

Anyone who has learned the principle of compilation knows , For static languages ( Such as Java、C++、C), Those who deal with these things are called compilers (Compiler), Correspondingly for JavaScript Such a dynamic language is called an interpreter (Interpreter). The difference between the two is summed up in one sentence : Compiler is to compile source code into another kind of code ( Like machine code , Or bytecode ), The interpreter directly parses and outputs the result of code running . For example ,firebug Of console It's just one. JavaScript Interpreter .

however , It's hard to define now ,JavaScript Engine is an interpreter or a compiler , because , Such as V8(Chrome Of JS engine ), It's actually to improve JS Operation performance of , Before running, it will JS Compile to local machine code (native machine code), And then execute the machine code ( That's a lot faster ), I'm sure you're right JIT(Just In Time Compilation) It must be no stranger .

I personally think , There is no need to over emphasize JavaScript What is the parsing engine , I think it's OK to know what it did . How does the compiler or interpreter understand the code , Just turn out the textbook of College compiling course . What I want to emphasize here is ,JavaScript The engine itself is a program , Code it . such as V8 Just use C/C++ Written .

2. JavaScript Parsing engine and ECMAScript What's the relationship ?

JavaScript The engine is a program , We wrote JavaScript Code is also a program , How to make the program read the program ? This requires defining rules . such as , Previously mentioned var a = 1 + 1;, It said :

  • On the left var It's a statement (declaration), It states a This variable
  • Dexter + To show that you want to 1 and 1 add
  • The middle equal sign indicates that this is an assignment statement
  • The last semicolon means that the sentence is over

These are the rules , With it, there is a standard of measurement ,JavaScript The engine can parse according to this standard JavaScript Code. . So here ECMAScript That's what defines these rules . among ECMAScript 262 This document , That's right JavaScript This language defines a complete set of standards . These include :

  • var,if,else,break,continue Is such as JavaScript Key words
  • abstract,int,long Is such as JavaScript Reserved words
  • How to count it as a number 、 How to call it string and so on
  • Defines the operator (+,-,>,< etc. )
  • Defined JavaScript The grammar of
  • Define the expression , Statements and other standard processing algorithms , For example, meet == How to deal with
  • ⋯⋯

The standard JavaScript The engine will implement according to this set of documents , Note that the standard is emphasized here , Because there are also things that are not implemented according to standards , such as IE Of JS engine . That's why JavaScript There will be compatibility issues . As for why IE Of JS The engine doesn't implement according to the standard , It's about browser wars , I won't repeat it here , On their own Google And .

therefore , To put it simply ,ECMAScript Defines the standard of language ,JavaScript The engine is based on it , This is the relationship between the two .

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

In short ,JavaScript The engine is part of the browser . Because browsers do a lot of other things , For example, parsing page 、 Render the page 、Cookie management 、 History, etc . that , Since it's part of , So in general JavaScript All the engines are developed by browser developers themselves . such as :IE9 Of Chakra、Firefox Of TraceMonkey、Chrome Of V8 wait .

So we can see that , Different browsers use different JavaScript engine . therefore , We can only say what we need to know more about JavaScript engine .

4. Why? JavaScript A single thread ?

JavaScript One of the characteristics of language is single thread , in other words , Only one thing can be done at a time . that , Why? JavaScript There can't be more than one thread ? This can improve efficiency .

JavaScript The single thread , Related to its use . As a browser scripting language ,JavaScript Its main purpose is to interact with users , And operation DOM. This determines that it can only be a single thread , Otherwise, it will bring complicated synchronization problems . such as , Assume JavaScript There are two threads at the same time , A thread in a DOM Add content on node , Another thread deleted this node , Which thread should the browser follow ?

therefore , To avoid complexity , From the birth ,JavaScript It's a single thread , This has become the core feature of the language , It won't change in the future .

To take advantage of multiple cores CPU Computing power ,HTML5 Put forward Web Worker standard , allow JavaScript The script creates multiple threads , But the child thread is completely controlled by the main thread , And do not operate DOM. therefore , The new standard has not changed JavaScript The nature of single threads .

Two 、 Task queue

Single thread means , All tasks are queued , The previous task is over , Will perform the latter task . If the previous task took a long time , The latter task had to wait .

If it's because it's computationally heavy ,CPU Hands are full , Also calculate , But a lot of times CPU Is idle , because IO equipment ( Input/output device ) Very slowly ( such as Ajax Operations to read data from the network ), We had to wait for the results , I'm going to keep going .

JavaScript The language designers realized , The main thread can be completely ignored IO equipment , Suspended pending tasks , Run the next task first . wait until IO The device returned the result , back , Carry on with the suspended task .

therefore , All tasks can be divided into two kinds , One is synchronous tasks (synchronous), The other is asynchronous tasks (asynchronous). Synchronous task refers to , Tasks queued for execution on the main thread , Only the previous task was completed , To perform the next task ; Asynchronous task means , Do not enter the main thread 、 And enter " Task queue "(task queue) The task of , Only " Task queue " Notification thread , Some asynchronous task is ready to execute , This task is then executed on the main thread .

say concretely , The operation mechanism of asynchronous execution is as follows .( So is synchronous execution , Because it can be seen as asynchronous execution without asynchronous tasks .)

(1) All synchronization tasks are performed on the main thread , To form a Execution stack (execution context stack).

(2) Outside the main thread , There is also a " Task queue "(task queue). As long as asynchronous tasks have run results , It's just " Task queue " Put an event .

(3) once " Execution stack " All synchronization tasks in are completed , The system will read " Task queue ", See what's going on inside . Those corresponding asynchronous tasks , So the waiting state is ended , Enter the execution stack , Start execution .

(4) The main thread repeats step 3 above .

3、 ... and 、 Events and callback functions

" Task queue " It's a queue of events ( It can also be understood as a queue of messages ),IO The device accomplishes a task , It's just " Task queue " Add an event to , Indicates that related asynchronous tasks can enter " Execution stack " 了 . Main thread read " Task queue ", Is to read the events in it .

" Task queue " In the event , except IO Beyond the event of the device , It also includes some user generated events ( For example, mouse click 、 Page scrolling and so on ). As long as the callback function is specified , When these things happen, they go into " Task queue ", Wait for the main thread to read .

So-called " Callback function "(callback), It's the code that will be hung by the main thread . Asynchronous tasks must specify callback functions , When the main thread starts executing asynchronous tasks , Is to execute the corresponding callback function .

" Task queue " It's a first in, first out data structure , The events at the front , Priority read by main thread . The reading process of the main thread is basically automatic , As soon as the stack is emptied ," Task queue " The first event on the thread automatically enters the main thread . however , Due to the existence of " Timer " function , The main thread first checks the execution time , Some events only arrive at the appointed time , To return to the main thread .

Four 、Event Loop

The main thread is from " Task queue " Read events in , The process is cyclical , So the whole operation mechanism is also called Event Loop( The event loop ).

Just to understand Event Loop, Please look at the chart below. ( Turn from Philip Roberts Speech 《Help, I'm stuck in an event-loop》).

Above picture , When the main thread is running , Make a pile (heap) And the stack (stack), The code in the stack calls all kinds of external API, They are " Task queue " Add all kinds of events (click,load,done). As long as the code in the stack is executed , The main thread will read " Task queue ", Execute the callback function corresponding to those events in turn .

Execute the code in the stack ( Synchronization task ), Always reading " Task queue "( Asynchronous task ) Before execution . Please see the following example .

Above picture , When the main thread is running , Make a pile (heap) And the stack (stack), The code in the stack calls all kinds of external API, They are " Task queue " Add all kinds of events (click,load,done). As long as the code in the stack is executed , The main thread will read " Task queue ", Execute the callback function corresponding to those events in turn .

Execute the code in the stack ( Synchronization task ), Always reading " Task queue "( Asynchronous task ) Before execution . Please see the following example .


var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function (){};
req.onerror = function (){};
req.send();

In the above code req.send The method is Ajax Operation to send data to the server , It's an asynchronous task , It means that only all the code of the current script is executed , The system will read " Task queue ". therefore , It is equivalent to the following .


var req = new XMLHttpRequest();
req.open('GET', url);
req.send();
req.onload = function (){};
req.onerror = function (){};

in other words , Specifies the part of the callback function (onload and onerror), stay send() The front or back of the method doesn't matter , Because they are part of the execution stack , The system always executes them , To read " Task queue ".

5、 ... and 、 Timer

In addition to events that place asynchronous tasks ," Task queue " You can also place timed events , That is to say, specify the time after which some code will be executed . It's called " Timer "(timer) function , That is, the code that is executed regularly .

The timer function is mainly composed of setTimeout() and setInterval() These two functions do , Their internal operation mechanism is exactly the same , The difference is that the code specified in the former is executed once , The latter is repeated execution . The following is the main discussion setTimeout().

setTimeout() Take two parameters , The first is the callback function , The second is the number of milliseconds to delay execution .


console.log(1);
setTimeout(function(){console.log(2);},1000);
console.log(3);

The execution result of the above code is 1,3,2, because setTimeout() Postpone the second line to 1000 In milliseconds .

If you will setTimeout() The second parameter of is set to 0, It means that the current code has been executed ( Perform stack clear ) in the future , Execute now (0 Millisecond interval ) The specified callback function .


setTimeout(function(){console.log(1);}, 0);
console.log(2);

The execution result of the above code is always 2,1, Because only after executing the second line , The system will execute " Task queue " The callback function in .

All in all ,setTimeout(fn,0) The meaning is , Specifies that a task is executed at the earliest available idle time of the main thread , in other words , As early as possible . It's in " Task queue " Add an event at the end of , So wait until the synchronization task and " Task queue " All the existing events are handled , Will be implemented .

HTML5 The standard stipulates setTimeout() The minimum value of the second parameter of ( Minimum interval ), Not less than 4 millisecond , If it's below this value , It will automatically increase . Before that , Old browsers set the minimum interval to 10 millisecond . in addition , For those who DOM The change of ( Especially when it comes to re rendering pages ), Usually not immediately , But every 16 Execute in milliseconds . Use this time requestAnimationFrame() The effect is better than setTimeout().

It should be noted that ,setTimeout() Just insert the event into " Task queue ", You have to wait until the current code ( Execution stack ) After execution , The main thread will execute its specified callback function . If the current code takes a long time , It could take a long time , So there's no way to guarantee , The callback function must be in setTimeout() At a specified time .

summary :

I used to think that javaScript It's just a simple scripting language , But as we went deeper, we found that ,javaScript It's still complicated , There are a lot of knowledge points ,JS The principle of execution is generally understood , But if you want to go deeper , More work is needed , Read more books , Efficient javaScript and javaScript Advanced programming is pretty good .

JavaScript Operation principle analysis of more related articles

  1. ( turn )Apache and Nginx Operating principle analysis

    Apache and Nginx Operating principle analysis original text :https://www.server110.com/nginx/201402/6543.html Web The server Web The server is also known as WWW(WORLD WID ...

  2. View Animation Operating principle analysis

    Android At present, the platform provides two kinds of animation , stay Android 3.0 Before , One big category is View Animation, Include Tween animation( Patch animation ),Frame animation( frame ...

  3. .NET CORE Learning notes series (5)——ASP.NET CORE Analysis of the operation principle of

    One . summary stay ASP.NET Core Before ,ASP.NET Framework The application is created by IIS load .Web The entry point of the application is determined by InetMgr.exe Create and call hosting , Triggered during initialization HttpApplicat ...

  4. JavaScript Operation principle

    i{margin-right:4px;margin-top:-0.2em}.like_comment_tips .weui-icon-success{background:transparent ur ...

  5. turn :Apache and Nginx Operating principle analysis

    Web The server Web The server is also known as WWW(WORLD WIDE WEB) The server , The main function is to provide online information browsing services . Application layer usage HTTP agreement . HTML Document format . Browser uniform resource locator (URL). Web clothing ...

  6. View Animation Animation Operating principle analysis

    I want to sort it out this time View Animation is also called patching animation (ScaleAnimation, AlphaAnimation, TranslationAnimation...) The process analysis of these animations . Content is not going to be analyzed ...

  7. Apache and Nginx Operating principle analysis

    Web The server Web The server is also known as WWW(WORLD WIDE WEB) The server , The main function is to provide online information browsing services . Application layer usage HTTP agreement . HTML Document format . Browser uniform resource locator (URL). Web clothing ...

  8. Reprint -Apache and Nginx Operating principle analysis

    This article is only for understanding Apache and Nginx A carding of knowledge , For more information, please read the blog in the reference link at the end of the article . Web The server Web The server is also known as WWW(WORLD WIDE WEB) The server , The main function is to provide online information browsing ...

  9. maven Internal operation principle analysis

    maven So far Java The de facto standard of programming language construction , Most of the projects are still using maven To build , So understand maven The principle of internal operation is very helpful for positioning and analyzing problems . This article mainly introduces some maven In the process of internal operation ...

Random recommendation

  1. MySQL Sub query and connection operation notes

    SQL Statements can be connected , In some complex data operations, connection operations must be used . In short, it's a SQL The result of a statement can be used as a connected SQL Part of the operation .SQL Structured query statements , Subqueries refer to all of the SQL operation , Is not ...

  2. java Regular expressions -- Get to know

    Learning goals The role of regular expressions, pattern matching of regular expressions Pattern Classes and Matcher To master the use of class String Support for regularization . Understanding regularization ( Why regular ) Easy to match data Perform complex string validation . Demolition ...

  3. be based on MySQL Protocol database middle layer project Atlas - 360 The team

    One . brief introduction Atlas By Qihoo 360 company Web Platform Department infrastructure team development and maintenance based on MySQL Data middle tier project of the protocol . It's in MySQL Officially launched MySQL-Proxy 0.8.2 Based on version , Revised ...

  4. Replace gitlab Public network IP, The breakdown caused .

    gitlab Replace the public network IP Address , Lead to gitlab It is too laggy , also ssh The way to add remote warehouse is unable to git pull perhaps git push, Only adding http The way can be normal git pull and git push ...

  5. MySQL AutoCommit The problems brought about by

    Phenomenon description It was found in the test that , service A After getting the service B Successful registration of users response in the future , Start calling the query user information interface , But I found that I couldn't find any results . Check binlog Find out , Before querying the request , The database is really done commit ...

  6. C Language _ Structure variable pointer as a function parameter use case

    # include <stdio.h> # include <stdlib.h> # include <string.h> # include <malloc ...

  7. Talking about surging In the service engine rabbitmq Component and containerized deployment

    1. Preface Finished last week surging Of 0.9.0.1 Update work , This version is available through nuget Download engine components , After downloading , No code is required build Integrate , The engine will go through Sidecar Patterns automatically scan and assemble heterogeneous components to build service engines ...

  8. JavaEESpringMVC Foundation finishing

    1. What is? SpringMVC ? Introducing what is SpringMVC Before , Let's see Spring Basic architecture . Here's the picture : We can see , stay Spring In the basic structure of , It's circled in red Spring W ...

  9. Windows 10 x64 Compile below Hadoop Source code

    Windows 10 x64 Compile below Hadoop Source code Environmental preparation Hadoop No official Windows 10 Installation package under , So you need to compile it manually , In official documents BUILDING.txt In file ...

  10. const And volatile

    C perhaps C++ Basically from top to bottom . Read from left to right . But for pointers, the declaration is inverted in a sense . C perhaps C++ Each statement in is made up of two parts : Zero or more declaration specifiers , One or more declarators separated by commas . cons ...