Thinking about the Event Loop of JS running mechanism from an example

Source: Internet
Author: User
Tags event listener

Chestnuts are as follows:

for (var i = 0; i < 5; i++) {    setTimeout (function () {        console.log (' I: ', i);        After one second the output has almost no time interval output of 5 5    }, 1000);} Console.log (i);                      Immediate Output 5

Presumably many people see the answer immediately, but why can't the timer print out the 1,2,3,4,5 in turn? The answer will be decided later.

So how exactly can we output the results we want in turn? Everyone might think of using closures, or a let statement in ES6, but we don't talk about it today.

Why is JS a single thread?

We all know that JS is different from other languages, it is single-threaded. So the question comes, why not multithreading? As a matter of principle, multithreading is not able to solve problems at the same time to raise efficiency? In addition to the multi-threaded conflict, preemption resources and other answers, what can it be?

In fact, this is related to its use as a browser scripting language, the main purpose of the browser scripting language is to interact with the user, will produce the DOM operation, this is the crux of the problem, assuming that JS is multi-threading, there is a thread is to delete the DOM operation, there is a current DOM add content, this time the browser should do? This determines that JS should be designed as a single thread. Does JS have the possibility of multithreading? The answer is yes, HTML5 presents the Web worker standard, however,

"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 doesn't change the nature of JavaScript single threaded "----Nanyi blog.

Second, event loop events

Because JS is single-threaded, so the execution time needs to queue, the previous task after the end of the next task will be executed, then if the previous task was executed for a long time, the latter task will wait for a long time. If some of the wait is not due to slow CPU calculation, such as the use of IO devices, then JS will wait for the task to suspend, perform the subsequent tasks, such as IO return results, and then back to perform a straight line suspended task.

This task has synchronous tasks and asynchronous tasks, which are tasks performed on the main thread, forming an execution stack (execution context stack), queued. Asynchronous tasks are not performed on the main thread, but in the task queue, and only when the main thread has completed all the synchronized tasks, the asynchronous task in the task queue goes to the main thread and is executed.

The asynchronous execution mechanism is as follows:---Ruan Yi Feng

Visual description of---MDN

On the main thread:

A function 1 is called, creates a stack frame, contains the parameters of function 1 and local variables, when function 1 calls the function 2, and creates a stack frame, this stack frame before the first stack frame, contains the parameters of function 2 and local variables. The main thread executes first the stack frame of the top layer (generated by function 2), and when function 2 returns, the corresponding stack frame is out of the stack, and then proceeds to the stack frame of function 1 until the stack is empty.

Message Queuing:
A JS runtime contains a pending message queue. Each message is associated with a function. When the stack is empty, a message is fetched from the queue for processing. This process involves invoking the function associated with the message (and thus creating an initial stack frame). When the stack is empty again, it means that the message processing is finished.

To add a message:

In the browser, adding an event can be when an event occurs and an event listener is bound, and the message is added at any time. It can also be when you call a function such as settimeout,

Add the message to the column after a certain time in the future.

SetTimeout:

When the function is called, a message is added to the message pair column after a certain time in the future, and if other tasks in the execution stack are not completed (assuming a time-consuming calculation), the settimeout message must wait until the execution stack's task is complete before it is processed. So the second parameter of the function represents only the least time, not the exact time.

Even if you set the 0 delay:

SetTimeout (function CB1 () {    console.log (' I am the second executed ');  }, 0);                            Console.log (' I was the first to be executed ');       Print this sentence first            

In fact, JS stipulates that the second parameter setting of the timer must not be less than 4ms, less than the words will be executed at the minimum 4ms.

, when the main thread runs, the heap (heap) and stack (stack) are generated, and the code in the stack calls various external APIs in the "any

Various events (Click,load) are added to the service 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.

Third, look back at the beginning of the chestnut

The For loop and the outside Console.log () are synchronous tasks on the main thread, they are executed sequentially, the For loop ends first (I becomes 5 at this time), and then the Console.log () is executed;

The settimeout in the For loop is in the task queue, which only waits until the stack in the previous main thread is empty, until a time is executed, when I in the scope becomes 5, when the callback function in settimeout reads I is 5.

One more question?

What is the time interval for output 5? The obvious answer is that printing a 5,1000ms immediately after almost simultaneous output of 5 5; why???

As explained above, for a loop once, a Settimeou task is added to the task queue (the task is to execute a callback function after 1000ms), so the loop ends with 5 settimeou tasks in the Task list, and when the stack is empty in the main thread, the task list starts to stack , wait for 1000ms to execute the callback, so the next 5 5 is printed almost at one point.

Then the sequence of JS execution can be summed up as:

Main thread (synchronous Task) = "Task Queue (Async) =" Callback

Thinking about the Event Loop of JS running mechanism from an example

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.