JavaScript to pull a few single-threaded correlation

Source: Internet
Author: User

JavaScript to pull a few single-threaded correlation

JavaScript is known to be single-threaded, which means that JavaScript can only handle one thing at a time. He's not like C,java, waiting for these many

threads, you can open different threads to handle multiple things at the same time.

So why are other languages so convenient to open multiple threads to perform multiple tasks simultaneously, but not JavaScript?

"The day will fall to the great people also, will first bitter its mind, labor its bones, hungry its body skin, empty its body, the line refers to disorderly its, so tempted endure sex, had benefited its cannot"-"Mencius"

It is because JavaScript carries a big mission, so he can only silently watch others have multi-threading. He acts as a browser scripting language, as long as the user is in

Line interaction/Processing front-end data/manipulation DOM.

Let's take a code example:

  function Adddom () {    var html = document.createelement ("div");    html.innerhtml = "This is div" +i;    document.getElementById ("mydiv"functionvar mydiv = document.getElementById ("mydiv"//if ( Mydin.childnodes[0]) {mydiv.removechild (mydin.childnodes[0//}}      

Note: The above Code comment section can make the logic more rigorous, here need to give an error has proved the point of view, so be annotated.

Executing the Adddom function according to the above code is the correct way to generate such a DOM, even if the Adddom function is still in the process of execution.

Deletedom,deletedom will also be executed after adddom execution, then you can complete a DOM add and delete operations, which is precisely because

For JavaScript is a single thread.

Now, if JavaScript can have multiple threads, then when we let a thread execute the Adddom function, the adddom is still in the process of executing

Line Deletedom, this time will open a thread to execute, when the browser brain short-circuit, it does not know which is the main ... If it's done first,

Deletedom, then the effect is to report the error has not reached the desired effect.

In summary, JavaScript does not apply to multi-threading, in order to interact, he can only endure (so when the error will not continue to execute, you do not spray

JavaScript, check the code you wrote is the right time to do it.

Event queuing and asynchronous execution

Since JavaScript is a single-threaded execution, there are a lot of things that need to be done to make sure you have to queue up. And then we're going to pull the crap. Event queue

and asynchronous.

The JavaScript event queue is the next event that is going to be executed one after the other, and the next one will be executed only if the current task is executed.

Works When we trigger an event, then this event will be added to the end of the list of events, of course, can not jump the queue, after all, is a citizen of the ~

The above is a brief introduction to the event queue, so what is asynchronous?

The JavaScript language divides the execution pattern of a task into two types: synchronous (synchronous) and asynchronous (asynchronous).

Synchronization is done in a methodical manner, in the order of the event queues.

Asynchronous is different, each task can have one or more callback function (callback), when the previous task is finished, do not go to the next task, first to perform its

The existence of the callback function, and the next task is not equal to the end of the previous task, the beginning of the execution, the execution sequence is not the same, resulting in asynchronous.

On the code:

  var num = 0;  function firstfn () {      num +=1;  };  functionif (value = = = 1//else{console.log ("the num still 0");}} firstfn (); SECONDFN (num) ;

The above can be printed normally, because the first function is executed, so NUM has been added 1, so the judgment takes effect.

  var num = 0function Firstfn () {setTimeout (function () {num +=1// Here we use settimeout to do asynchronous processing function SECONDFN (value) { if (value = = = 1); } else{console.log ("The num still 0"); //the num still 0}} firstfn (); SECONDFN (num);                

It's useless to do that again. Because SetTimeout put num++ 's event at the end of the event list, second (num) is in front of it,

So now the execution is to print the NUM still 0. So how does it prove that the event was put to the end? Look at the following code:

  <id= "mydiv" onclick= "addevent ()">click me</div>  
 var num = 0; function Firstfn () {setTimeout (function () {num +=1); }; function SECONDFN (value) { if (value = = = 1//the num is 1} else{ Console.log ("The num still 0" );}} FIRSTFN (); function Addevent () {SECONDFN (num);}     

When we click on the div with ID mydiv, the Click event will be triggered, the event will call the Addevent function, and the Addevent function will be at the end of the event queue

Join the new event that needs to be executed. When we click on the div, we will print the NUM is 1.

Empathy for understanding setinterval.

Below, incidentally, a question code that has been asked by a small partner:

The normal code:

  var i = 3;  For (; i>0;i--) {    console.log (i);  // Print Order: 3 2 1};    

"Unhealthy" code:

  var i = 3;  For (; i>0;i--) {    setTimeout (function () {console.log (i);},0);  // print order 0 0 0};     

People ask is why all set the delay time is 0, print out or not normal.

The usual description for settimeout: Given a callback and a delay of n milliseconds, SetTimeout will run the callback after n milliseconds.

So in most cases, this description can only be roughly correct and not completely correct.

And SetTimeout also comes with a hidden, large, small pit (which will be caused by thread blocking):

  New Date;  SetTimeout (function() {      new/// has several times printed with end time:1001 MS, which is still biased in case there is no other blocking and only runs this event},1000 );

So the n milliseconds described above will be biased in some cases.
Well, just write that much first. I have to go to work tomorrow, it's late today. or mobile phone editor, originally intended to sleep, write half did not complete, in the heart strange uncomfortable ...
If the understanding has the deviation, also hoped everybody feel free, everybody exchanges together can better progress.

JavaScript to pull a few single-threaded correlation

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.