Interviewer: What is the cycle of events?
As often take an examination of one of the knowledge of the interview, we should know the importance of the event loop, there are very, very much the article is about the event loop, but I always feel that not enough comprehensive, a lot of friend may know about the event loop after see execution mechanism, to understand what the synchronization task and asynchronous task, But the emergence of macro task, micro task confused, or it is a look to understand, do wrong. After reading this article, you will understand the cycle of events.
How do you fully understand the loop of events? Just understand the following six points!
1. What is an event loop?
2. Why is there an event loop?
3. What is the mechanism of the event loop?
4. What is the relationship between synchronous task, asynchronous task, macro task and micro task?
5. What are async and await in ES6?
6. Classic Interview questions (Let’s do them together)
1. What is an event loop?
First of all, Javascript is a single-threaded language, which means that when we write Javascript code, we run it line by line from top to bottom in the order we wrote it. An event loop is a single threaded execution mechanism for Javascript.
Why is javascript a single-threaded language?
Javascript has been defined since its birth for the user to interact with the browser. Let’s think about it. If we write JS code that has two operations, one is to add a DOM node to the document, and one is to delete that DOM node, if JS is multithreaded, How does the browser know if we want to add or remove DOM nodes first? Browsers probably don’t behave as we intended.
2. Why is there an event loop?
Js is a single thread of execution, if we write a js step (such as send a request to obtain a resource) because our network is slow, it takes a long time, do not we have to wait for the resource to be obtained before continuing to execute the following code? JS would block page rendering, which would make the user experience very bad, so the event loop was born. Smart javascript engines treat the JS code we are executing as a task, which can be divided into two broad categories:
-
Synchronization task
Synchronization tasks are js tasks that do not take much time to execute, so to speak, ordinary JS code.
-
Asynchronous tasks
Since synchronous tasks do not take much time, asynchronous tasks must take a lot of time to pull. For example, setTimeout is an asynchronous task (here is the first one, the full version below).
When executing JS, we will continue to execute synchronous tasks. If we encounter asynchronous tasks, we will first suspend it, and then put it into the task queue when it can be executed. Continue with the js task below so that the pull is not blocked! The detailed loop mechanism is shown below.
3. What is the mechanism of the event loop? (When there was no macro task, micro task concept)
To help understand the cycle of events, put up a picture that I think is really nice and popular on the Internet
SetTimeout: 2 seconds setTimeout: 2 seconds setTimeout: 2 seconds setTimeout: 2 seconds Wait for the main thread task to complete and then execute the process in the asynchronous task queue. It’s not intuitive, right? Let’s see, what does this code say?
First, our code will go to the main thread
- Line 1, synchronize the task
console.log('1')
1, print - Line 2, asynchronous task
setTimeout
After 300ms, the callback function is put into the asynchronous task queue for execution. What are the characteristics of queues? First in, first out) - Line 8.
console.log('4')
To print 4 - Similarly, the tasks on lines 9 and 12 are
setTimeout
The callback function is placed on the asynchronous task queue - Line 15,
console.log('7')
To print 7
After execution, the main thread, asynchronous task queue situation:
The main thread is then empty, and the task queue is placed on the main thread to execute in first-in, first-out order.
console.log('5')
, print 5 firstconsole.log('6')
And then print 6- then
console.log('2')
Print 2 againsetTimeout console.log('3')
Suspend again, and then put into the task queue - The main thread is still empty, and then the only one that was just put into the asynchronous task queue
console.log('3')
perform
So what’s the end result?
Results: 1,4,7,5,6,2,3
Isn’t that easy, actually? Let’s take a look at macro and micro tasks (really easy).
4. What is the relationship between synchronous task, asynchronous task, macro task and micro task?
Is a browser asynchronous task as simple as setTimeout? That’s impossible.
With the emergence of various asynchronous tasks, we have to classify all tasks of JS again, divided into macro tasks, micro tasks. (Macro and micro tasks perfectly fit all events, explaining the mechanism of event loops)
All tasks (including synchronous tasks and asynchronous tasks) are divided into macro tasks and micro tasks, and now there are two asynchronous tasks (macro task queue and micro task queue).
First, let’s look at macro tasks and micro tasks. (Found a very complete picture)
Although there are so many, in fact, there are only setTimeout, setInterval, Promise, but the other best to understand.
What about event loops explained by macro tasks and micro tasks? Look at the picture:
It’s the same code as before, but with two promises.
Start analyzing:
The first round:
- Home page, what is this whole code? Can be seen as
script
Contains code snippets ah, is a macro task. Put it directly into the main thread. - Line 1,
console.log('1')
1, print - Line 2,
setTimeout
Asynchronous macro task, put into the macro task queue - Line 8.
promise
There are asynchronous microtasks (then), put into the microtask queue - Line 13,
console.log('4')
To print 4 - Line 14,
setTimeout
Asynchronous macro task, put into the macro task queue - Line 22,
setTimeout
Asynchronous macro task, put into the macro task queue - Line 25,
console.log('7')
To print 7
In this case, the main thread, macro task queue and micro task queue are:
According to the principle of microtask priority
- perform
console.log('8')
(Microtask, the microtask queue is empty, the macro task will be executed, otherwise all the microtasks will be executed.) - perform
console.log('5')
(meetpromise console.log('9')
Put it in microtask queue, watch out!! Each macro task queue is checked to see if there are any tasks in the microtask queue after the task is finishedconsole.log('9')
, the implementation ofconsole.log('9')
, the microtask queue is empty, continue to execute the macro task. - perform
console.log('6')
Is there any microtask in the microtask queue? No, so continue with the macro task queue task - perform
console.log('2')
When the macro task printed 3 is put into the macro task queue, the micro task queue is asked whether there are micro tasks… No, proceed to the next task in the macro task queue - perform
console.log('3')
“, and asked if the microtask queue has microtasks… No, continue to execute the next task in the macro task queue, find no task, ok, execute finished.
So the result is:1,4,7,8,5,9,6,2,3
Didn’t understand buddy re-read it, pay attention to when execution to the task of micro empty the micro task queue is the only performs the task of macros, and every time a macro missions just from the macro task queue a macro task execution, performed and ask if there is any task, have is executed (performed all tasks), not the rest of the macro will continue to fulfill.
The conclusion is that the event loop is: execute all microtasks in the queue (and see if there are any macro tasks) -> execute all macro tasks in the queue (and see if there are any macro tasks) -> execute all microtasks in the queue (and see if there are any macro tasks)… This is the cycle of events
Do you understand?
5. What are async and await in ES6?
We can view these two things aspromise.then
In the form.
Such as:
Without further ado, if you are careful, these two results are equal, you can open the console and try.
6. Classic Interview questions (Let’s do them together)
Here’s a classic interview question (the answer is below the title) :
console.log('script start')
async function async1() {
await async2()
console.log('async1 end')}async function async2() {
console.log('async2 end')
}
async1()
setTimeout(function() {
console.log('setTimeout')},0)
new Promise(resolve= > {
console.log('Promise')
resolve()
}).then(function() {
console.log('promise1')
}).then(function() {
console.log('promise2')})console.log('script end')
Copy the code
Result: script start -> async2 end -> Promise -> script end -> asynC1 end -> promise1 -> promise2 -> setTimeout
The end
Ok, that’s the end of the loop! Did you learn?
If small partners find mistakes welcome to correct and discuss!
Give it a thumbs up if you think it’s okay