Written in front, this is I will begin to write a series, mainly in the framework of time, although USES the framework to work, but for the interview, and advanced technology, the basics of JS bedding is the icing on the cake, also had to learn a piece of knowledge, though the car does not need to be very good car, you just need to master automobile commonly used functions. But if you know cars, you can drive better, same thing. Of course, an article will not only talk about a knowledge point, generally will be linked to the knowledge point series, while recording their own learning, while sharing their own learning, mutual encourage! If possible, please also give me a like, your like can also make me work harder to update!

An overview of

  • Serving time: 10-15 minutes

  • Difficulty:simpleDon’t run look before you walk

  • Food value: understand why JS is single-threaded, understand why there is synchronous and asynchronous task division, understand what microtask and macro task are, which microtask and macro task in Event Loop to execute first, and finally try the best, the last question of the article

Single threaded JS

One of the things that you all know about JS is that it’s single-threaded.

So, why is JS single threaded, when multiple threads can improve efficiency?

In fact, this also has to do with its own use, the main use of JS is to interact with users, and manipulation of the DOM. This determines that it has to be single threaded, otherwise it will cause complex synchronization issues. For example, if JS has two threads at the same time, one adding content to a DOM node and the other removing the node, which thread should the browser use?

Single threading means that all tasks need to be queued until the previous task finishes before the next task is executed. If the first task takes a long time, the second will have to wait.

If you queue because the CPU is busy with a lot of computations, you can do that, but a lot of times the CPU is idle because the IO device (input output device) is slow (such as an Ajax operation reading data from the network) and you have to wait for the result to come out before you proceed.

The designers of the JavaScript language realized that it was perfectly possible for the main thread to suspend the waiting task and run the next task first, regardless of the IO device. Wait until the IO device returns the result, then go back and continue the suspended task. This leads to synchronous and asynchronous tasks

Thus, all tasks can be divided into two types, synchronous and asynchronous. A synchronous task is a task queued for execution on the main thread. Only after the previous task has been executed can the next task be executed. An asynchronous task is a task that enters a task queue instead of the main thread. The task queue notificates the main thread that an asynchronous task is ready to execute.

So, it was the advent of single threading that led to the emergence of synchronization and asynchrony. Let’s introduce a real-life example to help you understand both

The Event Loop is an Event Loop

Real life synchronization and asynchrony

For example, we usually eat KFC, we have to go to the cashier line, (don’t tell me to scan the code order!) , suppose that we ordered a chicken + payment for a minute, take food to five minutes, this time the clerk said, according to the regulation of our store, we can only one by one, service customers, the customer must wait for the current customer take meal, to replace a customer order, and this kind of situation, that is what is called a synchronization, is to execute sequentially, Do one thing before you move on to the next.

But the result is very obvious, this way of receiving customers is too low efficiency, the KFC is estimated to support today has gone bankrupt.

In order to improve its service efficiency, KFC later introduced order area and pick-up area. After you pay, you are given a receipt, and you can go out of the queue at the cashier, so that the next customer can order quickly, and you just need to wait for the reception to tell you that your meal is ready and come to the pick-up area to pick up your food.

JS synchronization and asynchrony

  • synchronous

    Tasks are executed from top to bottom, and the last task must wait for the last task to finish (the last person to order must wait for the last person to finish).

  • asynchronous

    The previous task is not finished (the previous person has not finished the food), it doesn’t matter, directly execute the next task (let the next customer order), wait until the reception notice to pick up the food, then execute (pick up the food)

After the division of synchronous tasks and asynchronous tasks, the running efficiency of the program is significantly improved (the reception efficiency of KFC)

Microtasks versus macro tasks

Synchronous tasks and asynchronous tasks have been divided. As we all know, synchronous tasks are executed sequentially, from the top down.

So, asynchronous tasks also have their order of execution, which is also from the top down, but in asynchronous tasks, there is a further division of asynchronous types, which is microtasks and macro tasks, remember that the microtasks execute before the macro tasks

  • Micro tasks (micro-task)

    Process. NextTick, Promise, MutationObserver, etc

  • Macro task (macro-task)

    SetTimeout, setInterval, setImmediate, Script (overall code), I/O operations, etc

It is worth noting that promises are a bit special because the code in the body of the Promise constructor is executed immediately, while promise.then () and promise.catch () are microtasks, namely resolve() and reject().

To understand this sentence, consider the following example

new Promise(function (resolve) {
  console.log(1)})Copy the code

The 1 in the above example code, which is output directly, belongs to the synchronization task, although it does exist in the Promise

After learning how to distinguish between microtasks and macrotasks, we also have a better understanding of the order of execution of asynchronous tasks

The call stack

This is the final role, where the actual code is executed, the task is performed

Event Loop

  1. Initially, the call stack is empty. The microtask queue is empty, and the macro task queue has only one script (the overall code). The first thing to be executed and queued is the overall code

  2. The overall code as macro tasks into the call stack, synchronous tasks and asynchronous tasks to distinguish

  3. Synchronous tasks are executed directly and out of the stack after execution. Asynchronous tasks are divided into micro tasks and macro tasks and pushed into micro task queue and macro task queue respectively

  4. After the synchronization task is finished (the call stack is empty), the microtask queue is processed and pushed into the call stack

  5. When the microtask queue in the call stack is processed (the call stack is empty), the macro task queue is pushed into the call stack until the call stack is empty again, and the cycle ends

The overall operation process can be viewed in the following figure. The red arrow is the main execution process. The overall code (macro task) => synchronization task => microtask queue => macro task queue

Although it is true that the overall code is initially executed as a macro task, it is important to remember that in asynchronous tasks, the microtask queue executes before the macro task queue.

In fact, this Event Loop involves a lot of knowledge, including microtask, macro task, call stack, execution context, synchronous and asynchronous, and task queue

A question at the end of the article

console.log(1)

setTimeout(function() {
  console.log(2)})new Promise(function (resolve) {
  console.log(3)
  resolve()
}).then(function () {
  console.log(4)
}).then(function() {
  console.log(5)})console.log(6)
Copy the code

Now, this is a very easy problem to solve. The answer is 1, 3, 6, 4, 5, 2

If you don’t understand, take a look at my analysis below, where we split the code from top to bottom into three parts: synchronous task, microtask queue, and macro task queue

  • Synchronization task

console.log(1)
console.log(3)
console.log(6)
Copy the code
  • Microtask queue

console.log(4)    //Promise.then()
console.log(5)    //Promise.then()
Copy the code
  • Macro task queue

console.log(2)    //setTimeout
Copy the code

So, the answer is immediately obvious: 1, 3, 6, 4, 5, 2

directory

  • This article understands JS series (a) compilation principle, scope, scope chain, variable promotion, temporary dead zone

  • This article understands JS series (2) JS memory life cycle, stack memory and heap memory, depth copy

  • JS series (3) to understand the garbage collection mechanism, memory leaks, closures

  • Understand JS series (four) closure application – Currie, partial function

  • Understand JS series (five) closure application – tremble, throttling

  • JS series (6) micro task and macro task, Event Loop

  • JS series (7) constructor, new, instance object, prototype, prototype chain, ES6 class

  • JS series (8) easy to understand the Promise

  • Learn more elegant asynchronous solutions in JS series (9)