“This is the 7th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

What are microtasks

Promise async and awaitCopy the code

What are the macro tasks

SetTimeout setInterval DOM event AJAX requestCopy the code

Look at the code below

<script> console.log(1) setTimeout(()=>{ console.log("2") },0) Promise.resolve().then(()=>{ console.log('3') }) Console. log(4) </script> we found that the order of printing is 1-4-3-2, so why is it in this order? I'm sure it's okay to print 1-4 first and then 2 because 3 is a Promise, and promises are microtasks. 2 is setTimeout, which is the macro task. The micro task executes earlier than the macro task. So we do 3 first and then we do 2Copy the code

My conclusion

Synchronous task before asynchronous task, micro task before macro task execution time is earlier than macro taskCopy the code

Say when the following code should be executed

Let app= document.getelementById ("app") let cont='<p> I am p tag </p>' Console. log(1) setTimeout(()=>{console.log("2") alert('setTimeout2')},0) Promise.resolve().then(()=>{ console.log('3') alert('3') }) console.log(4) </script> </body>Copy the code

Analysis of the execution of the above code

I'm going to do 1-4 and then I'm going to print 3 and pop up 3 and then I'm going to print 2 and pop up setTimeout2 because there's a DOM render between the microtask and the macro task so I'm going to do DOM render and then I'm going to pop up the macro task so after 1-4, DOM rendering is performed. And then output 2 and then setTimeout2Copy the code

Conclusion and application scenarios

We've all done echarts with this conclusion. We know when we render Echarts. After the DOM rendering of the page is complete, the node can be retrieved for rendering. So some people will request that the time be placed in the monuted() life cycle to ensure that the returned data will render properly on the page. Actually according to the conclusion above. You can request data entirely in Created. When you come back. DOM must be done rendering. Because the request is a macro task. Macro tasks are executed after DOM renderingCopy the code