preface

We all know that JavaScript is a single-threaded language: you can only run one task at a time. Normally that’s fine, but if you have one task that takes 30 seconds, why wait 30 seconds for all the other tasks? (Since JS runs on the main thread of the browser, the entire page is stuck for 30 seconds.)

Fortunately, browsers offer something that JS engines don’t: A Web API. It includes DOM APIS, setTimeout, HTTP requests, and more. All of these features help us handle asynchronous, non-blocking operations.

What is an Event loop?

Event Loop is an Event Loop, which is a mechanism of browser or Node to prevent Javascript from blocking when running in a single thread. It is also the principle of asynchronous.

Why do WE need to understand Event loop?

  • Add technical depth, which means understanding how Javascript works.
  • The technology in the front-end field is endless, and the underlying principles can be mastered unchanged.
  • To deal with a large interview, understand its principle, the topic of arbitrary play.

Pre-knowledge of data structures

Heap: A group of data maintained using a complete binary tree. It is a linear data structure, equivalent to a one-dimensional array, with a unique successor.

Stack: last in first out. Like tubs of potato chips, you can only put them in the top when you pack them, but you can only take them out when you eat them.

Queue: First in, first out. Similar to queuing for business, the first person in line to deal with the first.

Call stack: Essentially, of course, it is a stack of functions to be executed. Remember, functions! Let’s start with two functions:

  • The stack is empty
  • Now we go to A function A, and function A is pushed
  • Function A calls function B, and function B pushes
  • Function B exits the stack after execution
  • Then we continue to execute function A, and when we’re done, A also exits the stack
  • The stack is empty

Event loop

Synchronous and asynchronous tasks

Js single threads are divided into synchronous tasks and asynchronous tasks.

Synchronization tasks wait in the call stack for the main thread to execute in sequence.

The asynchronous task will put the registered callback function into the task queue after the asynchronous task has the result. When the call stack is empty, it will be read into the call stack and wait for the main thread to execute.

The callback function

A lot of people see “callback functions” and are ready to freak out, but it’s really simple. For example, a hotel offers a wake-up call service, but the guests are asked to decide how they want to wake up. It could be making room calls, sending a maid to knock on the door, sleeping too late to be delayed, or asking for a basin of water to be poured over your head. Here, the “wake-up call” is decided by the guest and told to the hotel, which will execute it the next morning. This “wake-up call” is the callback function. And the action that the guest tells the hotel how to wake up, that is, the action that the callback data is transferred into the library function, is called to register a callback function.

Macro task, micro task

In Js, tasks are divided into two types, Macro Task and Micro Task.

Macro tasks include:

  • Script all the code
  • setTimeout
  • setInterval
  • setImmediate
  • I/O
  • UI Rendering

Microtasks include:

  • Process. NextTick (unique) Node
  • Promise. Then the mission after
  • Mutation Observer

As you can see, there are both synchronous and asynchronous tasks in macro tasks.

Event Table

The Event Table can be interpreted as a Table of Event -> callback functions

It is a list of asynchronous events in JavaScript (request, setTimeout, IO, etc.) and their corresponding callback functions

Event Queue

An Event Queue is simply a Queue of Callback functions, so it is also called a Callback Queue

When an Event in the Event Table is triggered, the Event’s callback function is pushed into the Event Queue and waits to be executed

Event Loop

A flowchart to understand in seconds:

Event Loop rules, remember the rules, everything easy~

  1. Js execution uses two data structures, the call Stack and the Event Queue (both are software categories).

  2. Before execution, synchronous tasks are added to the execution stack in sequence according to the code sequence. Asynchronous tasks are divided into macro tasks and micro tasks and put into macro task queue and micro task queue respectively.

  3. In the execution of the synchronization task execution stack (as the first macro task), check whether the stack is empty, if the stack is empty, check whether the task queue is empty, if not empty, will be in accordance with the rules of fifo micro completing execution of the task, she will go the second macro tasks, each macro after the task has been completed, check whether the task queue is empty, If it is not empty, it will execute the next macro task after completing all the micro tasks according to the first-in, first-out rule, and so on.

  4. The code before the Promise. Then is a synchronous task, executed directly, and the code after the. Then is an asynchronous task, which is also a microtask, and needs to be put into the microtask queue.

Examples – Classic interview questions

setTimeout(function () {
    console.log(1)},0);

new Promise(function (resolve, reject) {
    console.log(2);
    resolve();
}).then(function () {
    console.log(3)
}).then(function () {
    console.log(4)});console.log(6);
Copy the code
  1. Perform the mainline step task: promise.then console.log(2) before; And console.log(6), output 2, 6
  2. SetTimeout to the macro task queue, promise. then to the micro task queue.
  3. Since step 1 performed the first macro task, now start the micro task, printing 3, 4
  4. Perform the next macro task: print 1

The final answer; 2, 6, 3, 4, 1

setTimeout(function () {
    console.log(1)},0);

new Promise(function (resolve, reject) {
    console.log(2)
    for (var i = 0; i < 10000; i++) {
        if (i === 10) {
            console.log(10)
        }
        i == 9999 && resolve();
    }
    console.log(3)
}).then(function () {
    console.log(4)})console.log(5);
// 2
Copy the code