Of the personal blog website welcome communication: firefly: https://blog.xkongkeji.com

The purpose of EventLoop

Js single-threaded

As a browser scripting language, JavaScript’s main purpose is to interact with users and manipulate the DOM. This means that it has to be single-threaded, which can cause complex synchronization problems. For example, if there are two threads of JavaScript at the same time, one thread adds content to a DOM node, and the other thread removes that node, which thread should the browser use?

Single-threaded solution

Single threading means that all tasks need to be queued until the first one is finished before the next one can be executed. If the first task takes a long time, the second task has to wait forever. If the queue is due to a large amount of computation and the CPU is too busy, it is fine, but many times the CPU is idle because the IO devices (input and output devices) are slow (such as Ajax operations reading data from the network) and have to wait for the results to come out before executing. That’s where EventLoop came in.

Where do macro and micro tasks come from

Micro tasks

  • Promise, which generates a microtask when promise.resolve () or promise.reject () is called.
  • A MutationObserver interface that listens for DOM node changes and generates a DOM change log microtask.
  • Process.nextTick (Node only)

Macro task

  • Render events (such as PARSING DOM, calculating layout, drawing)
  • User interaction events (such as mouse clicks, page scrolling, zooming in and out, etc.)
  • JavaScript scripts execute events
  • Network request completed, file read/write completed event

Execution sequence diagram (image from network)

Personal understanding

  • Js will execute the main thread task first, and put it into the microtask queue when it encounters the microtask, and put it into the macro task queue when it encounters the macro task.
  • When the main thread code is done it takes the microtask from the microtask queue until the microtask queue is empty,
  • After the completion of the microtask queue, the macro task will be taken out from the macro task queue for execution. (Personal understanding: the main thread code is the first macro task) Just like the main thread task, the microtask encountered will be put into the microtask queue, and the macro task encountered will be put into the macro task queue.
  • Repeat the process, and this is the event loop.