About js single thread, event loop, and micro task

About js single thread, event loop, and micro task

js single thread:

It is the order of execution in js, that is, js is executed in a single thread and can only be executed one by one. Next, let's take a look at some execution orders. Of course, except for asynchronous requests.
All tasks can also be divided into: asynchronous tasks and synchronous tasks.

console.log("event start");
   setTimeout(function () {
    
    
     console.log("setTimeout");
   });

   new Promise(function (resolve, reject) {
    
    
     console.log("promise start");
     resolve();
   }).then(function () {
    
    
     console.log("promise end");
   });
   console.log("event end");
   aa();
   function aa() {
    
    
     console.log("123");
   }

Here is the result

Insert picture description here
Thread: When you open a browser (application), the browser is a process. After opening the browser, there are many things to do (division of labor): sending requests, accepting requests, rendering pages, executing js, etc. These are all threads.

Event loop

Insert picture description here
When executing, he will first execute the synchronous main thread task and execute asynchronously.

Macro task and micro task

In the ES6 specification, microtasks are called jobs, macrotasks are called tasks.
Macro tasks are initiated by the host, and microtasks are initiated by JavaScript itself.

In ES3 and previous versions, JavaScript itself does not have the ability to initiate asynchronous requests, and there is no microtask. After ES5, JavaScript introduced Promise, so that the JavaScript engine itself can initiate asynchronous tasks without the need for a browser.

So, to sum up, the difference between the two is: the
Insert picture description here
Insert picture description here
macro task will trigger a new cycle.

Guess you like

Origin blog.csdn.net/weixin_54163765/article/details/112631289