JavaScript async, stack, event loop, task queue

Learning link address: https://segmentfault.com/a/1190000011198232

Difference analysis between timer nextTick() and setImmediate() in node.js

http://www.jb51.net/article/57882.htm

 

js is executed in a single thread. When js encounters asynchronous processing, it will add asynchronous processing to the task list. Only when the execution of the execution stack of the main thread is completed, the transactions in the task list will be executed.

In Js, there are two types of task queues: macro tasks and micro tasks. There can be multiple macro task queues and only one micro task queue. So what tasks will be assigned to which queue?

  • Macro tasks: script (global task), setTimeout, setInterval, setImmediate, I/O, UI rendering.
  • Micro tasks: process.nextTick, Promise, Object.observer, MutationObserver.

As we mentioned above, when the stack is empty, the task will be taken from the task queue to execute. There are 3 steps:

  1. Take a macro task to execute. After the execution is completed, the next step.
  2. Take a microtask to execute, and after execution, take another microtask to execute. Until the microtask queue is empty, execute the next step.
  3. Update UI rendering.
  4. The micro-task will be executed first, and the macro-task will be executed after the micro-task is executed.
  5. In the microtask, process.nextTick it is a special task, which will be directly inserted into the head of the microtask (of course, multiple tasks process.nextTick are also first-in, first-out), with the highest priority.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212574&siteId=291194637
Recommended