JavaScript EventLoop event loop

2020-01-11

EventLoop - event loop

1, Before learning the event cycle, learn a few English phrases

EventLoop event loop
 Event Queue
 Event Table
Macro task
Micro task

2, Another question of event mechanism

console.log(1);

setTimeout(() => {
  console.log(2);
  Promise.resolve().then(() => {
    console.log(3)
  });
});

new Promise((resolve, reject) => {
  console.log(4)
  resolve(5)
}).then((data) => {
  console.log(data);
  
  Promise.resolve().then(() => {
    console.log(6)
  }).then(() => {
    console.log(7)
    
    setTimeout(() => {
      console.log(8)
    }, 0);
  });
})

setTimeout(() => {
  console.log(9);
})

console.log(10);

// Correct results: 1, 4, 10, 5, 6, 7, 2, 3, 9, 8

Hahaha, I was shocked to see the above question. When Xiaotian's teacher sent it to me at that time, I was also shocked. It's really hard for me to be synchronous and asynchronous.

At that time, I sent my results to the teacher, and then ran it again. I found that I was wrong from the third one. ok, let's start from the event cycle mechanism and get to know the problem.

3, js event cycle, synchronous and asynchronous

First of all, js tasks are single threaded, everything must be done in order, and the tasks behind must wait in line. But tasks are divided into synchronous and asynchronous.

When a task block code executes,

  • When a synchronization task is encountered, it will enter the main thread,
  • When an asynchronous task is encountered, it will enter the Event Table to register the function, and then move the function to the Event Queue.
  • When the task in the main thread finishes executing, it will go to the Event Queue to read the asynchronous functions and execute them in order.

When the synchronization task of this code block is completed, the Event Table will execute the asynchronous tasks in sequence.

 

 

Source from https://juejin.im/post/59e85eebf265da430d571f89 Big guy

However, there is still a problem. In the Event Queue, micro tasks need to be executed first

4, js event loop, macro task and micro task

js events can also be divided into macro tasks and micro tasks

  • Macro task: including overall code script, setTimeout, setInterval
  • Micro task: Promise, process.nextTick

When a macro task enters the main thread

  • Judge whether the task is synchronous, asynchronous and synchronous
  • Asynchronous macro task, placed in Event Queue, asynchronous micro task, placed in Event Queue
  • When the main thread task is finished, go to the Event Queue
  • Enter the Event Queue to determine whether it is a micro task or a macro task. Execute the micro task first and then the macro task

 

Tuyuan comes from the big guy https://juejin.im/post/59e85eebf265da430d571f89

 

5, OK, after learning the event cycle, let's solve the problem at the beginning.

// macro1,Synchronous execution, printing 1
console.log(1);    

// macro2,Asynchronous macro tasks placed in Event Queue ,We mark it ascallback1(macro)
setTimeout(() => {
  // Synchronization task
  console.log(2);
  // Asynchronous micro task, we mark ascallback4(micro)
  Promise.resolve().then(() => {
    console.log(3)
  });
});

// macro3 Synchronize macro tasks
new Promise((resolve, reject) => {
  // Synchronous execution, printing 4
  console.log(4)
  resolve(5)
  // micro1,Asynchronous micro task to Event Queue,We mark it ascallback2(micro)
}).then((data) => {
  // Sync, print 5
  console.log(data);  
  // Asynchronous micro task, to Event Queue,We mark it ascallback5(micro)
  Promise.resolve().then(() => {
    console.log(6)
  // Asynchronous micro task, to Event Queue,We mark it ascallback6(micro)
  }).then(() => {
    console.log(7)
  // Asynchronous macro tasks, placing Event Queue,We mark it ascallback7(macro)
    setTimeout(() => {
      console.log(8)
    }, 0);
  });
})

// macro4,Asynchronous macro tasks placed in Event Queue ,We mark it ascallback3(macro)
setTimeout(() => {
  console.log(9);
})

// macro5,Synchronous task printing 10
console.log(10);


// Analysis:
// *** Enter the main thread. There are 5 macro task blocks of the main thread. Execute the synchronization task first

// 1. [Perform synchronization task]
//     (1).Print 1, 4, 10


// 2. Event Queue The functions of are:callback1(macro),callback2(micro),callback3(macro)

// 3. [Perform micro task first callback2(micro)]
//     (1).Performing synchronization tasks, printing 5, printing console.log(data),The result is 5, data yes resolve Result
//     (2).callback5(micro)
//     (3).callback6(micro)
//     (4).callback7(macro)

// *** Now it has printed: 1, 4, 10, 5
// *** Event Queue The functions of are:callback1(macro),callback3(macro),callback5(micro),callback6(micro),callback7(macro)
// *** There are two micro tasks, which are executed successively

// 4.[Micro task]
//     (1).callback5(micro)Print 6
//     (2).callback6(micro)Print 7

// *** Now it has printed: 1, 4, 10, 5, 6, 7
// *** Event Queue The functions of are:callback1(macro),callback3(macro),callback7(macro)
// *** Next in turn

// 5. [Macro taskcallback1(macro)]
//     (1).Performing synchronization, printing 2
//     (2).callback4(micro)

// *** Now it's printed: 1, 4, 10, 5, 6, 7, 2
// *** Event Queue The functions of are:callback3(macro),callback7(macro),callback4(micro)
// *** Next, perform the micro task

// 6. [Micro taskcallback4(micro)]
//     (1).Print 3

// *** Now it's printed: 1, 4, 10, 5, 6, 7, 2, 3
// *** Event Queue The functions of are:callback3(macro),callback7(macro)
// *** There are two remaining macro tasks, which are executed in turn

// 7. [Macro taskcallback3(macro),callback7(macro)]
//     (1).Print 9
//     (1).Print 8

// *** Now it's printed: 1, 4, 10, 5, 6, 7, 2, 3, 9, 8
// *** All numbers have been printed out after the task is completed

 

ok, this learning is over here! Let's have another exercise!

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})

 

If you don't learn, you can go to see the explanation of the big man https://juejin.im/post/59e85eebf265da430d571f89

Tags: Javascript

Posted on Sat, 11 Jan 2020 02:59:38 -0500 by nutstretch