This is the 25th day of my participation in Gwen Challenge

preface

Event loops are often asked by interviewers because they measure how well an interviewer knows about execution stacks, task queues, macro tasks, micro tasks, etc. I also read a lot of articles, but every time I feel a little bit swallowed, or after reading forgot, today take this opportunity to review it again.

Event loop

First of all, js is single threaded, which means that after one task is executed, the next task is executed, in order. However, if the task is a time-consuming one, the thread is blocked and subsequent tasks cannot be executed. To prevent this:

Js divides tasks into synchronous tasks and asynchronous tasks

To summarize: Perform synchronous tasks first, then asynchronous tasks. Repeat as before.

List some synchronization tasks:

console.log(1);
console.log(2);
console.log(3);
for(let i = 4; i <= 10; i++) {
  console.log(i)
}
function test () {
 console.log(11)
}
test()
Copy the code

After the command is executed, the output from 1 to 11 is displayed in sequence.

List some asynchronous tasks:

setTimeout(() = > {
  console.log(1)},1000)
Promise.resolve(2).then((i) = > {
  console.log(i)
})
console.log(3)
Copy the code

And you can see that the output order is 3, 2, 1

Asynchronous tasks

Asynchronous tasks are divided into micro tasks and macro tasks.

Microtasks have these:

  • process.nextTick(Node)
  • Promise.async.await
  • MutationObserver

Macro tasks have these:

  • Script (whole code)
  • setTimeout
  • setInterval
  • I/O operations
  • setImmediate(Node)
  • requestAnimationFrame

process

Here’s how it works:

  • Loading script code
  • Distinguish between synchronous and asynchronous tasks
  • The main thread performs the synchronous task first, forming an execution stack. If it encounters an asynchronous task, it distinguishes between macro and micro tasks and pushes its callback into the respective task queue
  • After the main thread completes the synchronous task, it checks the asynchronous task queue and executes the micro task first. After the micro task queue, it executes the macro task queue.
  • Repeat the above process

Microtasks are executed before macro tasks

The following is an example to analyze:

async function async1() {
  console.log('async1 start');
  await async2();
  console.log('async1 end');
}
async function async2() {
  console.log('async2');
}

console.log('script start');

setTimeout(function() {
  console.log('setTimeout');
}, 0);

async1();

new Promise(function(resolve) {
  console.log('promise1');
  resolve();
}).then(function() {
  console.log('promise2');
}).then(function() {
  console.log('promise3');
});

console.log('script end');

Copy the code

The output order is:

  • script start
  • async1 start
  • async2
  • promise1
  • script end
  • async1 end
  • promise2
  • promise3
  • setTimeout

Did you do it right?

Analysis:

  • First, execute the synchronization task first and output itscript start'
  • And then meetsetTimeoutPush it into an asynchronous macro task
  • Then performasync1And the outputasync1 startAnd then you seeasync2To performasync2Because it is internal synchronization task, direct outputasync2Because async2 isawaitFunction, so push the rest of the code into an asynchronous microtask
  • And then meetPromise.resolveBefore it was synchronized, outputpromise1,thenPart of it in asynchronous microtasks
  • Then it encounters the synchronization code and outputsscript end
  • After the main thread tasks are all executed, the asynchronous microtask queue is executed and outputasync1 end.promise2.promise3
  • After the execution of the micro task queue, execute the macro task queue and outputsetTimeout

What’s the difference between browser and Node event loops

The execution timing of the microtask queue is different in the browser environment and Node environment.

  • In browser environment, microtask task queue is executed in macro task.
  • In the Node environment, microtask queues are executed between stages of the event cycle

conclusion

The above is the Event Loop I summarized, hoping to help you understand ~