preface

I wrote this column because I recently wanted to reorganize my front-end knowledge systematically. I will try to write some business related tips and front-end knowledge of the key content, core ideas.

Micro task, macro task, when I first graduated, I didn’t hear much about it. I don’t know why interviews seem to have suddenly become common in recent years. Today we are going to look at what is microtask, macro task.

EVENT LOOP

To talk about micro tasks, macro tasks, you can’t avoid talking about Event loop first. We all know that JavaScript code is run in a single thread in a browser or nodeJS. In order to avoid blocking tasks (such as setTimeout wait time, in fact, can do other tasks), JS uses a mechanism called event loop.

Simply put, when the process starts, there will be a task queue in the program, and THE JS program executes tasks one by one in order. But in order to avoid blocking, we have what are known as asynchronous tasks. When an asynchronous task is encountered, the program does not execute immediately. Instead, it will be placed in the asynchronous task team, so that it will wait for the completion of the asynchronous task to see if there are any tasks that can be executed, and if so, it will be put into the main program to execute.

Here’s an example:

console.log(1);
setTimeout(() = >{
    console.log(2);
},100);
setTimeout(() = >{
    console.log(3);
},0);
console.log(4)
/ / output
/ / 1
/ / 4
/ / 3
/ / 2
Copy the code

As in the above example, the JS program reads and executes line by line, but after the setTimeout asynchronous task is executed, the contents of the callback task will be put into the asynchronous task queue, and then added to the main task queue after the asynchronous task can be executed.

Conclusion:

  1. When an asynchronous task is encountered, the asynchronous task is placed in a wait queue first.
  2. When a task in the waiting queue is ready to be executed, it is added to the main queue. Therefore, the execution order of wait queue tasks has nothing to do with the joining order.

What is a microtask, a macro task?

Once you’ve looked at Event loops, you can see that there are synchronous and asynchronous tasks in event loops. Their execution logic is to encounter an asynchronous first-off queue. This seems to suffice for the entire Event loop.

However, in fact, there are two types of tasks in the execution of asynchronous tasks, namely [micro task] and [macro task]. And there is an important rule in their execution order — micro tasks first, then macro tasks. As long as there are executable tasks in the microtask queue, the next macro task must wait for the executable microtask to complete.

Macro task type

task The browser Node
I/O
setTimeout
setInterval
setImmediate
requestAnimationFrame

Microtask type

task The browser Node
process.nextTick
MutationObserver
Promise.then catch finally

Let’s revise our model again according to the above rules

When there is content in the microtask queue, the task must be completed before the macro task is executed. Note: If the microtask completes, a new microtask is created during the execution of the macro task. At this time still need to follow this rule, the first execution of the micro task, to execute a macro task!

Why distinguish between microtasks and macro tasks?

The JS mechanism treats tasks as if they should be unequal. This means that faster tasks should be able to jump the queue without waiting for them to finish. At a lower level:

  • Microtasks are fast switching between threads. You can quickly complete all microtasks at once without context switching.
  • A macro task is a switch between processes that is slow and requires context switching for each execution. Therefore, only one macro task is performed in an Eventloop.
  • Microtask execution is fast, many can be executed at one time, and the effect of pseudo synchronization can be achieved by clearing the microtask immediately after the execution of the current macro task, which plays a crucial role in the rendering effect of the view.

While views are often rendered after macro tasks are executed, performing microtasks first ensures that data is updated before the view is rendered.

practice

console.log('aaa');

setTimeout(() = >console.log('t1'), 0);
(async() = > {console.log(111);
  await console.log(222);
  console.log(333);
  setTimeout(() = >console.log('t2'), 0);
})().then(() = >{
  console.log(444);
});

console.log('bbb');
/ / output
//aaa
/ / 111
/ / 222
// bbb
/ / 333
/ / 444
// t1
// t2
Copy the code

In the example above, there are macro tasks T1, T2. Micromissions 333,444.

  1. First, synchronize aaa output.
  2. Join the queue when macro task T1 is encountered.
  3. Synchronous output 111,222.
  4. On microtask 333, join the queue.
  5. Join the queue when macro task T2 is encountered
  6. On microtask 444, join queue
  7. BBB output is synchronized. The synchronization is complete.
  8. Back to perform the microtask first, output 333,444. End of microtask
  9. Execute macro task, output T1, T2.

async/await

Async /await = async/await This is actually promise’s domain of knowledge. Because essentially they’re the syntactic candy of Promise. So we need to know one small detail — the contents of the promise parentheses are synchronized. Then comes microtasks.

p = new Promise((res,rej) = >{
    console.log(1);
    res('ok');
    console.log(2);
}).then((res) = >{
    console.log(res);
})

console.log(3)
/ / output
/ / 1
/ / 2
/ / 3
/ / 4
Copy the code

Likewise async/await

(async() = > {console.log(1);
 await console.log(2);
 console.log('ok')
})()

console.log(3)
/ / output
/ / 1
/ / 2
/ / 3
/ / 4
Copy the code

That should help you get the hang of it.

conclusion

Microtasks, macro tasks are actually the result of event loops. It’s not hard in itself, just remember the micro before the macro. But Event Loop is a complex JS mechanism. Interested friends can consult their own understanding. The purpose of this article is to give you a quick and easy way to understand these concepts. Knowing this is enough for an interview, but it has little impact on our day-to-day work. It is worth noting that event loops are different in browsers and NodeJS. This article is hosted in the browser by default, and the nodeJS event loop will be placed in the [NodeJS] category later.

reference

Juejin. Cn/post / 684490…

Juejin. Cn/post / 689407…

Juejin. Cn/post / 684490…

www.ruanyifeng.com/blog/2013/1…