In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how to master the JavaScript implementation mechanism, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.
Why JavaScript is single-threaded
If we want to understand why JavaScript is single-threaded, we need to start with what JavaScript is used for.
As a scripting language for browsers, JavaScript is produced for browsers to interact with users and manipulate DOM elements, so as to enhance users' sense of interaction and experience. JavaScript manipulates the DOM element of the browser, so that JavaScript cannot become a multithreaded language. Let's assume a scenario where two threads operate on a DOM element at the same time, one thread needs to edit and update the DOM element, and the other is to delete the DOM element node. Which should the browser prevail?
You can only do the same thing at a time, because single threading is the core and feature of the JavaScript language because of manipulating the DOM element.
HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but child threads are completely controlled by the main thread and cannot operate on DOM. Even this change does not change the nature of js single-threading.
Synchronization and asynchronism in JavaScript
The single-threaded mechanism of javaScript results in only one thing being done at a time. Just like a bunch of people withdraw money at the ATM machine, no matter how many people in the back are in a hurry, they can only wait in line one by one, waiting for the first person to withdraw the money before it is the second person's turn.
However, if the previous task takes too long, the second task will wait for a very long time. For example, we need to load an Ajax request with a very large amount of data, and we have to wait for the result of the request before moving on to the subsequent task.
So how do we deal with this situation? Since we can't change the single-threaded mechanism of JavaScript, can we temporarily suspend some time-consuming tasks and wait until the main task is completed before executing these mounted tasks? The authors of JavaScript also came up with the idea that JavaScript has both synchronous and asynchronous tasks.
A synchronization task is that a task is queued on the main thread, and the next task must wait for the previous task to be completed before it can be executed. The asynchronous task means that the task does not enter the main thread, but enters the task queue (task queue) to wait. Only when the task enters the task queue notifies the main thread that an asynchronous task can be executed, the task will enter the main thread to execute.
Third, Event Loop event cycle mechanism
All synchronization tasks of JavaScript are executed on the main thread, forming an execution stack.
Task queue is a first-in, first-out principle. Events in the first queue are executed first, and events in the queue are executed later.
Event Loop
Perform the synchronization tasks in the execution stack.
When an asynchronous task is encountered, it will not wait for its return result all the time. Instead, it will suspend the asynchronous task temporarily and continue to execute other synchronous tasks.
When an asynchronous task has a result, JavaScript will add the task to the task queue. The tasks added to the task queue will not be called back for execution immediately, but wait for the main thread (execution stack) to be idle before joining the execution stack for callback execution.
Wait for the task in the execution stack to finish execution.
Add the tasks in the task queue to the execution stack and execute them.
Over and over again, it forms an infinite event loop. (the following figure is from the network)
After learning Event Loop, let's take a look at the following question:
SetTimeout (function () {console.log ('setTimeout start')}); new Promise (function (resolve) {console.log (' promise start'); resolve ()}). Then (function () {console.log ('promise then')}); console.log (' script end')
Try to analyze according to the JavaScript execution mechanism that we just learned above.
1. First, the synchronous task is executed to the setTimeout, but the setTimeout is a temporary suspension of the asynchronous task, waiting for the timing timeout to be added to the task queue.
two。 Continue, in the execution of new Promise,new Promise inside is the synchronization task, print "promise start".
3. Add .then to the task queue after executing to resolve.
4. Execute console.log ('script end'); print "script end".
5. At this point, the main task has been executed, and the asynchronous task is added to the main task to execute directly, print "setTimeout start", then add .then to the main task, and print "promise then".
So the result should be: promise start-> script end-> setTimeout start-> promise then?
After executing it in the browser, the result is not like this, but promise start-> script end-> promise then-> setTimeout start.
Macro task and micro task
Then why the above results are not consistent with what we expected, and why setTimeout start will print after promise.
In fact, it is because there is a sequence of asynchronous execution. In fact, it is not accurate to divide the execution order of task queues in an asynchronous and synchronous way. It should be divided into micro tasks and macro tasks.
Macro task (macro-task): script code, setTimeout, setInterval
Micro tasks (micro-task): Promise, process.nextTick
So setTimeout is a macro task in an asynchronous task, while Promise is a micro task in an asynchronous task. Whether it is a micro task or a macro task, it will enter the corresponding Event Queue, and then we will take a look at a flowchart.
Let's have a little understanding:
1. Perform macro tasks (script code)
two。 When a micro task is encountered while executing a macro task, it will be added to the Event Queue
3. After the execution of the current macro task is completed, the Event Queue of the micro task is checked and all the micro tasks in it are executed in turn.
4. After performing all the micro tasks, proceed to the first step to cycle through
This is also the operating mechanism of javaScript, combined with this, let's re-analyze the above example.
1. First, I hold the macro task (script code) and encounter the Event Queue that setTimeout added to the macro task.
two。 Continue, after executing to new Promise, print "promise start".
3. In the execution to resolve,.then is the micro task, which is added to the Event Queue of the micro task.
4. Execute console.log ('script end'); print "script end".
5. At this point, the execution of this round of macro tasks is all over. At this time, find out if there are any executable micro tasks in the Eevent Queue of the micro task, and find that an amount has just been added in the third step. Then, execute and print "promise then".
6. At this time, the first round of event loop is completely over. The next round of event loop first executes a macro task and finds that there is an added setTimeout in the Event Queue of the macro task. Execute and print "setTimeout start".
Always remember that JavaScript is single-threaded, was, is, and always will be. All the multithreading claims are bullshit.
Even Event Queue is not only the way to implement asynchrony, but also the execution mechanism of js.
Can be realized with JavaScript in the future. Will be implemented in JavaScript.
What is JavaScript JS is the abbreviation of JavaScript, it is a literal scripting language, its interpreter is called JavaScript engine, is a part of the browser, mainly used for web development, can add a variety of dynamic effects to the website, make the web page more beautiful.
The above content is how to master the JavaScript implementation mechanism, have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.