Four concepts

Before learning about Event Loop, there are a few concepts you need to understand

1. Javascript is single-threaded

Single thread means that our JS code can only be executed synchronously from top to bottom, and only one task can be executed at a time. This will cause some tasks with long execution time or uncertain execution time to block the normal execution of other tasks. Event Loop is introduced to solve this problem.

2. Task queues

To solve the above queuing problem, with the task queue, the browser will add the asynchronous task to the task queue after it has the result for future execution, and other tasks will be executed synchronously on the main thread.

Note here that the time to add a task to the task queue is after the asynchronous task has a result. In fact, the callback function of asynchronous task exists in the task queue.

3. Synchronous and asynchronous tasks

The synchronous task in THE Js program refers to the task executed in the main thread, and the asynchronous task refers to the task in the task queue

4. Javascript execution stack

All synchronization tasks are executed on the main thread as a stack. When the task execution on the main thread is complete, the task is removed from the task queue to execute.


var name = "zhouwei";

setTimeout(() => {
    console.log(1);
}, 1000);

console.log(name);
Copy the code

The code above is executed in the browser as follows. We understand the code of the program’s global execution environment as wrapped in a main function. The execution stack of this code changes as shown in the following figure:

  1. Start executing the code, pushing the main task (global code for execution) when asynchronous tasks are encountered (after setTimeout).
  2. The browser takes over the asynchronous task and adds the result of the asynchronous task (the callback function) to the task queue after 1s.
  3. The synchronization task in the execution stack is complete. The task queue is empty (less than 1s) and the execution stack is empty
  4. After an asynchronous task has a result, it is first queued in the task queue (because there may be many asynchronous tasks).
  5. The execution stack fetches the task from the task queue to start synchronous execution.
  6. Repeat Step 5.

Event Loop

The Event Loop is the process in which the Js execution stack continuously reads and executes tasks from the task queue

We know that the task queue stores the results of asynchronous tasks, so what are the asynchronous tasks?

1, events,

There are many events in Javascript, all of which are asynchronous tasks. The browser takes over. When the event is triggered, the callback of the event is added to the task queue and executed when there is no task in the Js execution stack.

Http request 3, timer 4, requestAnimationFrame, etc

Macrotasks and Microtasks

After understanding the task queue and Event Loop, we know that the Js execution stack reads the task execution from the task queue, but we are not clear about this specific project. The concept of macro task and micro task is introduced here to help us understand the Event Loop.

Asynchronous task callbacks into the task queue are divided intoMacro taskandMicro tasks.Js execution stackperformMacro taskandMicro tasksThe rules are shown in the figure below.

Js execution stack first performs a macro task (global code) -> reads all microtasks from the task queue -> UI rendering -> reads one macro task from the task queue -> all microtasks -> UI rendering ->…

At the end of each round of Event Loop (1 macro task + all micro tasks), the browser starts rendering interface (UI rendering is not performed if there is UI rendering required). After the UI rendering is completed, the next round of Event Loop begins.

What are macro tasks?

  • setTimeout
  • setInterval
  • setImmediate (Node)
  • RequestAnimationFrame (browser)
  • I/O (Event callback)
  • UI Rendering (Browser rendering)

What are microtasks?

  • Promise
  • process.nextTick (Node)
  • MutationObserver (a web interface provided by modern browsers to detect DOM changes)

SetTimeout delay problem

In general, in code setTimeout the callback execution time is greater than the set time. This is because after the time specified by setTimeout, although the callback function is added to the task queue, there may be a task being executed in the Js execution stack at this time, and the callback has a chance to execute after the task in the Js execution stack is completed, which is the problem of setTimeout delay.

In actual combat

Practice the output of the following code:


console.log(1);

setTimeout(() => {
    console.log(2);
    Promise.resolve().then(() => {
        console.log(3)
    });
});

new Promise(resolve => {
    console.log(4);
    setTimeout(() => {
        console.log(5);
    });
    resolve(6)
}).then(data => {
    console.log(data);
})

setTimeout(() => {
    console.log(7);
})

console.log(8);
Copy the code

Use the js implementation mechanism we mentioned above to analyze this problem:

1: Execute synchronous code output in global task:

1

4

8

Note that the Handle that Promise accepts is a synchronous task, while the THEN method is an asynchronous task, so it prints 4 directly.

2: There are three setTimeout macro tasks and one Promise micro task in the task queue

SetTimeout (() => {console.log(2); Promise.resolve().then(() => { console.log(3) }); }); setTimeout(() => { console.log(5); }); setTimeout(() => { console.log(7); }) // Then (data => {console.log(data); })Copy the code

Execute a microtask with output: 6

3: Then execute the first macro task


setTimeout(() => {
    console.log(2);
    Promise.resolve().then(() => {
        console.log(3)
    });
});
Copy the code

Output: 2

In this macro task, a microtask is added to the task queue. The task queue now has a new microtask.

4: performs a microtask. Output: 3


then(() => {
   console.log(3)
});
Copy the code

5: Executes tasks based on the rules. The output is 5 and 7

The overall output is:

One, four, eight, six, two, three, five, seven

Is that your answer?

conclusion

  • Javascritp tasks are divided into synchronous tasks and asynchronous tasks
  • Synchronization task inThe main thread(Js execution stack), the asynchronous task is taken over by another thread, and after the asynchronous task has a result, its callback is added to the task queue.
  • The tasks in the task queue are divided into macro tasks and micro tasks.Js execution stackAlways perform one macro task before completing all microtasks…