preface
JavaScript is a single-threaded, non-blocking scripting language that allows only one piece of code to execute at a time. In a single-threaded mechanism, when an asynchronous task is executed, the following code cannot be executed while waiting for the result to return.
When JS executes code, it does not wait for the asynchronous task to complete, but executes the synchronous task first. So how does JS do this?
This article will cover the above issues in detail, and you are welcome to read this article if you are interested.
Event loop
Single thread
Before we talk about event loops, let’s understand why JS is not designed to be multithreaded.
Let’s assume that if JS is multi-threaded, and JS has a DOM API to manipulate the DOM, then if there are two threads operating on the same DOM, thread 1 removes the DOM node, and thread 2 wants to manipulate the DOM, there will be a conflict as to which thread is dominant.
To avoid this, JS is designed to be single-threaded.
Macro and micro tasks
The JS engine classifies all tasks into two categories: macro tasks and micro tasks.
The macro tasks are:
script
The overall code- SetTimeout and setInterval
- I/O
- The UI rendering
- postMessage
- MessageChannel
- requestAnimationFrame
- SetImmediate (Node. Js environment)
Microtasks include:
- new Promise.then()
- MutaionObserver
- Process. NextTick (Node. Js environment)
Execute rules
In this article, we learned about the disadvantages of single thread. JS uses the EventLoop mechanism to solve the disadvantages.
- All code enters the main thread execution stack as macro tasks and begins execution
- During execution, the synchronized code is executed immediately, and the macro task enters the macro task queue and the micro task enters the micro task queue
- The current macro task is queued and read the microtask queue. If so, it will be executed until all the tasks are completed
- Perform browser UI process rendering
- Check whether there are webworker tasks and execute them
- This round of macro task execution is complete, go to step 2, continue to execute until the macro task and micro task queue are all cleared
For example
After we understand its execution rules, let’s take an example to illustrate, as follows:
console.log("1"); // 1 sync code: execute immediately [1]
setTimeout(function() {
console.log("2"); // 3 Synchronize code execution to execute output 2
process.nextTick(function() {
console.log("3"); // 4 Enter microtask queue [3]
});
new Promise(function(resolve) {
console.log("4"); // 3 Synchronize code execution to execute output 4
resolve();
}).then(function() {
console.log("5"); // 4 Enter microtask queue [3, 5]
});
});
process.nextTick(function() {
console.log("6"); // 2 enter the microtask queue [6]
});
new Promise(function(resolve) {
console.log("Seven"); // 1 macro task: execute immediately [1, 7]
resolve();
}).then(function() {
console.log("8"); // 2 enters the microtask queue [6, 8]
});
setTimeout(function() {
console.log("9"); // 5 macro task: Execute immediately [9]
process.nextTick(function() {
console.log("10"); // 6 enter microtask queue [10]
});
new Promise(function(resolve) {
console.log("11"); // 5 macro task: execute immediately [9, 11]
resolve();
}).then(function() {
console.log("12"); // 6 enter microtask queue [10, 12]
});
});
// Order of execution: 1 7 6 8 2 4 3 5 9 11 10 12
Copy the code
Process.nexttick () is a method in Node that you can think of as a microtask like promise, and the synchronization code in promise’s executor function executes immediately.
Let’s analyze the order of execution of the above code, as shown below:
The running result is as follows:
Once you’ve read through the sample code above, you should understand the js event loop mechanism.
, of course, you may not be so quick to gnaw through the example, the conceptual, the best way to master it is: the sample code in the editor, contrast the event loop execution rules, the line to read the code, going over the brain to guess the results, and then to execute code judge whether the results are consistent with your guess.
Finally, try to find some circular interview questions on the Internet, and you’ll know everything you need to know. Good Luck!
The code address
This article is “JS principle learning” series of the fifth article, this series of complete route please move: JS principle learning (1) “learning route planning
For all the sample code in this series, go to jS-learning
Write in the last
At this point, the article is shared.
I’m an amazing programmer, a front-end developer.
If you are interested in me, please visit my personal website for further information.
- If there are any errors in this article, please correct them in the comments section. If this article helped you, please like it and follow 😊
- This article was first published in nuggets. Reprint is prohibited without permission 💌