Why is JS single-threaded? 10-minute understanding of the JS engine execution mechanism

Source: Internet
Author: User

In-depth understanding of JS engine execution mechanism
    • Why is 1.JS single-threaded? Why is async required? How is a single thread implemented asynchronously?
    • Event loop in 2.JS (1)
    • Event loop in 3.JS (2)
    • 4. Talk about SetTimeout
First, keep in mind 2 points:

(1) JS is a single-threaded language

(2) JS's event loop is the execution mechanism of JS. In-depth understanding of the execution of JS is equivalent to a deep understanding of JS in the event loop

1. Why is JS single-threaded? Why is async required? How is a single thread implemented asynchronously?

The advent of technology is closely related to the real-world application scenario.

In the same way, we're going to answer these three questions with a real-world scenario.

(1) Why is JS single-threaded?

JS was originally designed to be used in the browser, so imagine if the browser JS is multi-threaded.

12345 scene description :   Now there are 2 processes ,process1 process2jsdom  process1 removed dom process2 edited the dom 2 conflicting commands How is the browser going to do that?

In this way, it is easy to understand why JS is designed as a single thread.

(2) Why does JS need to be asynchronous?

1234 Scenario Description : If there is no async in JS , only top -down execution, if the previous line parsing time is very long , then the following code will be blocked. for users , blocking means "stuck", which results in a poor user experience

Therefore, there is asynchronous execution in JS.

(3) JS single-threaded How to achieve asynchronous?

Since JS is single-threaded, can only be executed on one thread, and how to implement asynchronous?

Is the event loop, which understands the execution mechanism of JS by understanding the events Loop mechanism.

Event loop in 2.JS (1)

Example 1, observing its order of execution

1234567 console. Log(1)      setTimeout(function(){ console. Log(2) },0) console. Log(3)

Operation Result: 1 3 2

In other words, the function in settimeout is not executed immediately, but deferred for a period of time, after satisfying certain conditions, only to execute, such code, we call asynchronous code.

So, here we first know a way to classify JS, that is, the task is divided into: synchronous tasks and asynchronous tasks

Picture description

According to this classification method: JS execution mechanism is

    • 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 goes into the main thread and executes until the main thread is idle to see if there is an executable asynchronous task in the event queue, and if so, pushes it into the main process

Above three-step loop execution, this is the event loop

So the above example, can you describe the order in which it was executed?

12345 console. Log(1) is a synchronous task , put into the main line thread setTimeout() is an asynchronous task that is placed into the event tableand pushed into the event queue after 0 seconds console. Log(3 is the sync task , put it on the main line thread When 1, 3 after the control bar is printed , the main thread goes to the event queue to see if there is an executable function , executes Functions in the settimeout

Event loop in 3.JS (2)

So, the above about event loop is my understanding of the JS execution mechanism until I meet the following code

Example 2:

1234567 setTimeout(function(){ console. Log(' timer started ') }); New Promise(function(resolve){ console. Log(' Execute for Loop now '); For (var i = 0; i

Try to follow the JS execution mechanism we just learned above to analyze

1234567 SetTimeout is an asynchronous task that is placed in the event table new Promise is a synchronous task that is placed in the main process and executes directly on the print console. Log(' Execute for Loop now ') . Then the function is an asynchronous task that is placed in the event table console. Log(' End of Code execution ') is a synchronous code that is placed in the main process and executed directly

So, the result is "execute the FOR loop now-code execution is over-the timer starts-do the then function"?

Executed in person, the result is not so, but "immediately execute for loop-code execution end-Execute then function-Timer started"

So, is it the order of execution of asynchronous tasks, not the order, but the other provisions? In fact, it is not accurate to classify asynchronous and synchronous methods.

and the exact partitioning method is:

    • MACRO-TASK (Macro Task): Includes overall code Script,settimeout,setinterval
    • Micro-task (Micro Task): Promise,process.nexttick

According to this classification method: JS execution mechanism is

    • 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 sequence.

Repeating the above 2 steps, combined with event loop (1) event loop (2), is a more accurate JS execution mechanism.

Try to analyze example 2 according to the execution mechanism of just learning:

1234567891011121314 First ExecuteScript Macro Task , encounter SetTimeout, put it into the "queue" of the macro task Met New promise direct execution , print "Execute for Loop Now" Metthen method , is a micro task , put it into the "queue" of micro-task Print "End of code execution" This round of macro task is completed, look at the micro-tasks in this round and find a function in the then method that prints "Execute then function" To this, the event loop for this round is all done. In the next round of loops, perform a macro task first , find the "queue" in the macro task has a function in the settimeout , execute the print "timer starts "

So the final order of execution is "execute the For loop right now-code execution is over-execute then function-Timer starts"

4. Talk about SetTimeout

What does this paragraph of settimeout code mean? We generally say: after 3 seconds, the function in settimeout will be executed.

123 setTimeout(function(){ console. Log(' executed ') }, +)

But this is not rigorous, the exact explanation is: After 3 seconds, the function in settimeout will be pushed into the event queue, and the event queues (events) task, only when the main thread is idle to execute.

So only meet (1) 3 seconds later (2) The main thread is idle, and when satisfied, only 3 seconds after the function is executed

If the main thread executes a lot of content and executes for more than 3 seconds, such as executing for 10 seconds, then the function can only be executed in 10 seconds.

Why is JS single-threaded? 10-minute understanding of the JS engine execution mechanism

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.