EventLoop, message queue, macro task, micro task
  • JS asynchronous programming

The execution environment of JavaScript language is single-threaded, and only one task can be executed at a time. Multiple tasks need to be queued, which may block the code and lead to inefficient code execution. To avoid this problem, asynchronous programming emerged. The code is organized by callback callback function, event publish/subscribe, Promise, etc. In essence, asynchronous code is stored and executed by callback function.

  • EventLoop EventLoop and message queue

    EventLoop is a circular mechanism that continuously polls a number of queues to find tasks that need to be executed and execute them in order.

    Message queues are queues that store macro tasks, such as method references that are passed in when timer time is up, and ajax callbacks that are executed after that time.

    The entire script is initially executed as a macro task. During the execution, the synchronized code is executed directly. When the waiting time of macro task reaches or succeeds, the callback of the method is put into the macro task queue, and the micro task enters the micro task queue.

    Check and empty the microtask queue after the macro task of the current main thread is queued. The browser UI thread is then rendered, and the Web worker task is checked and executed.

    Then pull out a macro task to execute. And so on…

  • Macro and micro tasks

    A macro task can be understood as a macro task (including fetching an event callback from the event queue and placing it on the execution stack each time the code executes).

    The browser rerenders the page after the completion of one macro task and before the start of the next, so that the internal MACRO tasks and DOM operations can be executed in an orderly manner.

    Macro tasks include script(overall code), setTimeout, setInterval, I/O, UI interaction events, and MessageChannel

    Microtasks can be understood as tasks that need to be executed immediately after the completion of the current task. That is, perform the clean microtask after the current task but before rendering.

    So it responds faster than the macro task because you don’t have to wait for UI rendering.

    Microtasks include promise. then, MutaionObserver, process.nexttick (Node.js environment), etc