编程知识 cdmana.com

javaScript Event loop

1.JavaScript It's a single thread language , Single thread means that it has only one stack , You can only do one thing at a time , So if you want to know how he handles asynchronous problems, you have to figure out JavaScript The code execution and running mechanism of .

  First of all, let's write a simple synchronization thread code

 function one(n){console.trace(n);}
 function tow(n){one(n)}
 function three(n){tow(n)}
 three(3)

 

As shown in the figure callStack In is the code in execution , We use console.trace() Print this call station (callStack) The situation of , The execution result in the figure below shows that the calling order of functions is a rule of last in first out .

 

 

 

2. So how does it solve the asynchronous problem ?(task queues

Let's start with a concept     “ Task queue task queues)“

From the following code we can know settimeout It will delay execution by one second , He will be put into a task queue before execution (task queues), It's not going to be executed directly , wait for callStack  When all the events in are completed  event loop I'm going to take taskQueues Turn the event in to callStack In the implementation of

console.log('start');

setTimeout(()=>{
    console.log('waiting')
}
, 1000)

console.log('end');

  Output results                                       because setTimeout There is no return value, so he will throw it first undefined Wait another second and print

 

 

 3. Asynchronous queues also have execution priorities !(Microtasks

1.macrotask

 

 

  Among the tasks waiting for callback, they also have two kinds of tasks ,macrotask queue That's what we often say task queue.Macrotask It includes setTimeout, Dom operation click/onLoad/mouse Event binding ,fetch then response This kind of operation . In fact, these are all provided by browsers API, So when executing, there are their separate threads to operate . for instance ,setTimeout() Set up 2s Delay of , It's the browser that sets up timer To time , Another thread is waiting 2 second ,js The main thread is not affected ,2s After the callback function enters task queue.

(function() {

  console.log('this is the start');

  setTimeout(function cb() {
    console.log('this is a msg from call back');
  });

  console.log('this is just a message');

  setTimeout(function cb1() {
    console.log('this is a msg from call back1');
  }, 0);

  console.log('this is the end');

})();

 

 

 event loop The first returned task will be put into callstack in   If cb If and cb1 If there is no time difference, it will be executed in the order of FIFO

2.Microtask

ES6 Provides Promise For asynchronous operation .microtask. As above, there is also a queue (job queue) To deal with it microtask.job queue Have a higher priority . Every task After the end , Will check microtask Whether the queue has tasks waiting to be executed , According to FIFO , Execute sequentially .

console.log('script start');

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

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

 

 

  because macrotask Queues (task queues) Than   Microtask  Queues (job queues) Low priority, so setTImeout Print content of the last execution

3. summary event loop

eventloop  When callstack To check if the queue has a task to perform when it is empty , The execution order follows the first in first out rule , Executive Microtask(Promise) Queue ratio macrotask(setTimeout/DOM events/fetch) Queue priority is high ,Microtask  The tasks in will be performed first , When Microtask Only after all the queue tasks in are executed can they be executed macrotask Tasks in the queue , Of course, the biggest premise is callstack It has to be done first

while (queue.waitForMessage()) {
  queue.processNextMessage();
}

  

 

版权声明
本文为[Tao Feifan]所创,转载请带上原文链接,感谢

Scroll to Top