preface

JavaScript is designed to interact with browsers as a single-threaded, non-blocking scripting language.

  • Single threading means that at any point in code execution, there is only one thread to process a task.

  • Non-blocking in JS, the JS engine does not wait for an asynchronous event to return. Instead, it suspends the event until the result of the asynchronous task returns and then executes the corresponding callback according to the rule.

Event loop mechanism

First, the JS parser parses the JS code from top to bottom, pushes all the tasks onto the execution stack, and then executes them from scratch. When a synchronous task is encountered, it is executed in sequence. If an asynchronous task is encountered, the event will be suspended js. After the asynchronous event returns the result, the event will be added to the event queue. All tasks in the stack to be executed are completed, and the main thread is executing asynchronous tasks.

Asynchronous Task classification

The above event loop is just a macro representation, but asynchronous tasks are different. Asynchronous tasks are divided into macro tasks and micro tasks, and the two tasks have different execution priorities (micro task priority and macro task).

  • Macro Task

    • setInterval()
    • setTimeout()
  • Micro tasks

    • new Promise()
    • new MutaionObserver()

As mentioned earlier, after an asynchronous task returns a result, the JS parser adds the event callback to the event queue, actually to the macro task queue or microtask queue depending on the type of the event. And when the call stack is empty, the micro task queue event is executed first, and the macro task queue event is executed later.

Synchronous and asynchronous, blocking and non-blocking