“What will be hot and what to learn in 2022? This article is participating in the” Talk about 2022 Technology Trends “essay campaign.

Hi, I’m Ned👀, a junior with less than two years of experience at 🌹

The road ahead is still long 🎉, work hard to refuel it ❤~

Keep checking out my interview column, Ned’s Interview Gas station

preface

Macrotasks and microtasks are asynchronous concepts in JavaScript. If you are still confused about them, follow me through to make a better impression.

As always, the picture above:

Combing this part is mainly to make the logic of code execution more clear, of course, some reasons or to deal with some interview questions.

What are macro tasks and what are micro tasks?

Let’s start with the question, which should be a common one:

    console.log(100)
    setTimeout(() = >{
        console.log(200)})Promise.resolve().then(() = >{
        console.log(300)})console.log(400)
    // The answer is 100, 400, 300, 200
Copy the code

The question is, what is the order in which this code is printed after it’s executed? If the result in your mind is not the same as the answer, don’t panic. First of all, if you know something about synchronous asynchrony, you can see that there is no problem with printing 100, 400 first. The problem should be 200 and 300, why is 300 printed earlier than 200?

Asynchrony has something to do with the order in which you appear, not the different types of asynchrony

This is why setTimeout is above the promise, but 200 is printed after 300. If I print a setTimeout of 200 immediately after I print a setTimeout of 222, then between the same setTimeout, the print order is determined by the order in which you write it (remember the timing is consistent).

So the different types are macro tasks and micro tasks. Let’s take a quick look at which are macro tasks and which are micro tasks:

  • Macro tasks: setTimeout, setInterval, Ajax, DOM events
  • Microtasks: Promise, async/await

Microtasks are executed earlier than macros! (You can take a note of that, and I’ll come back to this later)

Dom events are not asynchronous operations, but they rely on the Eventloop mechanism, so they fall under this category

As you can see, the combination of macro tasks and micro tasks is what we call asynchronous. Remember the result directly first, and then explore why. Seeing this, you can go back to the previous problem. SetTimeout is a macro task, and Pormise is a micro task, and the micro task is executed earlier than the macro task, so print 300 first and then print 200.

Eventloop and DOM rendering

Eventloop and DOM rendering are related to why macro tasks are executed later than micro tasks, so let’s figure that out first. Here’s another example:

    const div1 = $('<div>1234</div>')
    const div2 = $('<div>1234</div>')
    const div3 = $('<div>1234</div>')
    const div4 = $('<div>1234</div>')
    const div5 = $('<div>1234</div>'The $()'#divs').append(div1).append(div2).append(div3).append(div4).append(div5)
    console.log('length', $(divs).children().length) / / 5
Copy the code

We create div with js, add it to a node, and immediately print the number of sub-elements of the node. After executing these lines, we can see that 5 is printed and 5 paragraphs are displayed on the page.

But what we’re trying to get at here is when our eyes see these five paragraphs.

One thing to understand is that DOM rendering is the rendering of DOM structures or JS operations to the browser for our eyes to see.

In fact, if we only execute this section of JS, by the time we print the action, we can print 5, but at the moment we can’t see the five new paragraphs on the page. So we need the opportunity to perform this DOM rendering process, and we need to understand the eventloop process.

Basically, there are a few things in EventLoop that we’ll talk about in more detail.

First of all we know, js is single-threaded, according to the order on line, if a particular line error, stop the follow-up executed, then is to perform synchronization, to implement the asynchronous, look at the picture, we will sync code one line in the Call Stack, asynchronous, will move into Web APIs, bide your time, If the time is right, move it to the Callback Queue. If the synchronous code is finished (i.e. the Call Stack is empty), DOM rendering will be attempted, and the Event Loop will be triggered. The Event Loop will start to search for the Callback Queue. If so, move it to the Call Stack for execution.

Please note: try to render the DOM, because there is probably no DOM modification in this section of JS, try means if there is manipulation on the DOM, then render, otherwise, ignore this step.

Why are macro tasks executed later than micro tasks

Alert blocks JS execution as well as DOM rendering. Using this, we can intuitively see who comes first and when DOM rendering is executed.

    // Microtasks: execute before DOM rendering
    Promise.resolve().then(() = > {
        const length = $('#divs').children().length
        alert(Micro task `${length}`)})// Macro task: execute after DOM rendering
    setTimeout(() = > {
        const length = $('#divs').children().length
        alert(` macro task${length}`)})Copy the code

The difference between macro and micro tasks

Again, from an Eventloop point of view, let’s look at setTimeout first

The first step is to enterWeb APIsWait for the opportunity, then enterCallback Queue, waiting forEventLoopThe mechanism is triggered and executed, while trying DOM rendering is just fine and stuckCall StackWhen you are free, follow upEventLoopThe middle of the mechanism, that’s why, rightsetTimeoutThe reason for executing after DOM rendering

Then we look at promise.then

Promises are ES6 spec, not W3C spec, so they don’t go through Web APIs, and unlike macro tasks, they have their own unique Micro Task Queue. Why?

  • Microtasks are mandated by ES6 syntax
  • Macro tasks are specified by the browser

Different specified places lead to different storage positions, so there are different storage positions in the picture.

So our EventLoop should end up like this:

When the Call Stack is empty, the current microtask is performed, DOM rendering is attempted, and EventLoop is triggered to execute the macro task.

Ask questions

After learning to see their own will not?

  • What are macro tasks and micro tasks?
  • Why do microtasks trigger earlier?
  • How do microtasks relate to DOM rendering?
  • Microtasks macro tasks and DOM rendering, process in EventLoop?

The end!

Macro and micro tasks are a big part of JavaScript asynchrony, so get started!

Comb every knowledge point, steady and steady, will not be the interviewer asked 😰~

If this article is wrong, please point it out in the comments section, thanks for correcting 🔔

This is the second article in my interview column, which will continue to be sorted out gradually. Please pay attention to 📢

👉 Column address: Ned’s Interview Gas station 👈

If you think the above content is good, you might as well click a like to support oh ~~😇

See you next time at 👋