JS event loop (Event Loop)

Description:

Javascript is a non-blocking single-threaded scripting language;

Browser is a multi-process system to process its allocation of resources (CPU, memory), open Chromethere will be a primary process, each open a Tabpage there is a separate process;

JavaScript synchronization task into tasks and asynchronous tasks, all the tasks are synchronized into the main execution stack (execution form a stack execution context stack), the result of waiting tasks callback enter into a task queue (task queue), until the main execution stack the task to finish before the task queue of asynchronous tasks, asynchronous tasks will be inserted into the main execution stack, will enter again next asynchronous task completes a cycle, throughout the implementation process, we called the event cycle. Task queue is divided into macro-task (macro task) and micro-task (micro tasks), in the latest standards, they are referred to as task and jobs.

macro-task probably include:

  • Script (overall code)
  • setTimeout
  • setInterval
  • setImmediate
  • I / O
  • UI rendering

micro-task probably include:

  • process.nextTick
  • Promise
  • Async / Await (actually the promise)
  • MutationObserver (html5 new features)

Overall execution flow chart:

 

 

 

 

 

async / await execution order Note:

输出:script start => async2 end => Promise => script end => promise1 => promise2 => async1 end => setTimeout

 

Analysis of this code:

 

  1. Executing code, output script start.
  2. Execution async1 (), calls async2 (), then the output async2 endat this time will be retained context async1 function, and then jump out async1 function.
  3. Encounter setTimeout, generate a macro task
  4. 执行Promise,输出Promise。遇到then,产生第一个微任务
  5. 继续执行代码,输出script end
  6. 代码逻辑执行完毕(当前宏任务执行完毕),开始执行当前宏任务产生的微任务队列,输出promise1,该微任务遇到then,产生一个新的微任务
  7. 执行产生的微任务,输出promise2,当前微任务队列执行完毕。执行权回到async1
  8. 执行await,实际上会产生一个promise返回,即 let promise_ = newPromise((resolve,reject){ resolve(undefined)})
  9. 执行完成,执行await后面的语句,输出async1 end
  10. 最后,执行下一个宏任务,即执行setTimeout,输出setTimeout

 

 

新版的chrome浏览器中不是如上打印的,因为chrome优化了,await变得更快了,输出为:

 

而await后面跟的是一个异步函数的调用,比如上面的代码,将代码改成这样:

 

 输出:script start => async2 end => Promise => script end => async1 end => promise1 => promise2 => async1 end setTimeout

 

 未写完,后续待更新...

 

Guess you like

Origin www.cnblogs.com/babyfacer/p/12306026.html