Javascript operation mechanism Event Loop

Javascript operation mechanism Event Loop

1. Four concepts

1. JavaScript is single-threaded

Single-threaded means that our js code can only be executed synchronously from top to bottom, and only one task can be executed at the same time. This will cause some tasks with long execution time or uncertain execution time to block the normal execution of other tasks. The reason why Event Loop appears is to solve this problem.

2. Task Queue

In order to solve the above-mentioned queuing problem, a task queue is created. When the browser has an asynchronous task with a result, it will be added to the task queue for future execution, and other tasks will be executed synchronously on the main thread.

It should be noted here that the timing of adding tasks to the task queue is after the asynchronous task has a result. In fact, what exists in the task queue is the callback function of the asynchronous task.

3. Synchronous tasks and asynchronous tasks

Synchronous tasks in Js programs refer to tasks executed in the main thread, and asynchronous tasks refer to tasks that enter the task queue.

4. Javascript execution stack

All synchronous tasks are executed on the main thread, forming an execution stack. When the task on the main thread is completed, the task is taken out from the task queue for execution.

var name = "zhouwei";

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

console.log(name);


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

  • Start executing the code, push the main task (global code into the stack for execution), and when encountering an asynchronous task (after setTimeout ).
  • The browser takes over the asynchronous task and adds the result of the asynchronous task (callback function) to the task queue after 1 second.
  • The synchronization tasks in the execution stack are completed. At this time, the task queue is empty (less than 1 second) and the execution stack is also empty.
  • After an asynchronous task has a result, it first enters the task queue (because there may be many asynchronous tasks).
  • The execution stack takes the task out of the task queue and starts executing it synchronously.
  • Repeat step 5.

Event Loop

The process of Js execution stack continuously reading tasks from the task queue and executing them is called Event Loop

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 an event is triggered, the event callback is added to the task queue and executed when there is no task in the Js execution stack.

  • 2. Http request
  • 3. Timer
  • 4. requestAnimationFrame, etc.

macrotask and microtask
After understanding the task queue and Event Loop , we know that the Js execution stack reads tasks from the task queue for execution, but we are not clear about this specific project. Here we introduce the concepts of macrotasks and microtasks to help us understand Event Loop.

The asynchronous task callbacks entering the task queue are divided into macrotasks and microtasks. The rules for the Js execution stack to execute macrotasks and microtasks are shown in the figure below.

The Js execution stack first executes a macro task (global code) -> reads all micro tasks from the task queue -> UI rendering (browser rendering interface) -> reads a macro task from the task queue -> all micro tasks -> UI rendering -> …

After each round of Event Loop ends (1 macro task + all micro tasks), the browser starts rendering the interface (if there is a UI that needs to be rendered, otherwise UI rendering is not performed). After UI rendering ends, the next round of Event Loop starts.

What are macrotasks?

  • setTimeout
  • setInterval
  • setImmediate (Node)
  • requestAnimationFrame (browser)
  • I/O (Event callbacks)
  • UI rendering (browser rendering)

What are microtasks?

  • Promises
  • process.nextTick (Node)
  • MutationObserver (a web interface provided by modern browsers for detecting DOM changes)

setTimeout delay issue

Generally speaking, the execution time of the callback in setTimeout in the code is greater than the set time. This is because after setTimeout specified time arrives, although the callback function is added to the task queue, there may be tasks being executed in the Js execution stack at this time. This callback needs to wait until the tasks in the Js execution stack are completed before it has a chance to execute. This is setTimeout delay problem.

3. Actual combat

Practice the following code output:

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);

Use the js execution mechanism we mentioned above to analyze this question:

1: Execute the synchronous code output in the global task:

1
4
8

It should be noted here that the handle function accepted by Promise is a synchronous task, while the then method is an asynchronous task, so 4 will be output directly.

2: At this time, there are three setTimeout macro tasks and one Promise micro task in the task queue.

// The macro task at this time is setTimeout(() => {
    console.log(2);
    Promise.resolve().then(() => {
        console.log(3)
    });
});

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


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

// At this time, the microtask is then(data => {
    console.log(data);
})

Execute a microtask, output: 6

3: Then execute the first macro task

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


Output: 2

In this macrotask, a microtask is added to the task queue. At this point the task queue has a new microtask.

4: Execute a microtask, output: 3

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


5: Continue to execute the task according to the rules, output: 5, 7

The overall output is:

1, 4, 8, 6, 2, 3, 5, 7

Is this your answer?

Summarize:

  • javascritp tasks are divided into synchronous tasks and asynchronous tasks
  • Synchronous tasks are executed in the main thread (Js execution stack), asynchronous tasks are taken over by other threads, and after the asynchronous tasks have results, their callbacks are added to the task queue.
  • Tasks in the task queue are divided into macrotasks and microtasks. The Js execution stack always executes a macro task first, and then executes all micro tasks...

This is the end of this article about the Event Loop of Javascript operation mechanism. For more relevant content about the Event Loop of Javascript operation mechanism, please search the previous articles of 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of JavaScript operation mechanism and a brief discussion on Event Loop
  • Detailed explanation of the event loop (Event Loop) of JavaScript operation mechanism

<<:  How to implement paging query in MySQL

>>:  The basic principles and detailed usage of viewport

Recommend

JavaScript gets the scroll bar position and slides the page to the anchor point

Preface This article records a problem I encounte...

Navicat connects to MySQL8.0.11 and an error 2059 occurs

mistake The following error occurs when connectin...

MySQL 8.0 WITH query details

Table of contents Learning about WITH queries in ...

How to use CSS media query aspect-ratio less

CSS media query has a very convenient aspect rati...

How to solve the element movement caused by hover-generated border

Preface Sometimes when hover pseudo-class adds a ...

How to use mixins in Vue

Table of contents Preface How to use Summarize Pr...

Introduction to container data volumes in Docker

Table of contents Docker container data volume Us...

React Native JSI implements sample code for RN and native communication

Table of contents What is JSI What is different a...

JavaScript implements constellation query function with detailed code

Table of contents 1. Title 2. Code 3. Results IV....

The difference between HTML name id and class_PowerNode Java Academy

name Specify a name for the tag. Format <input...

DD DT DL tag usage examples

We usually use the <ul><li> tags, but ...

Implementation of Vue single file component

I recently read about vue. I found a single-file ...

MySQL FAQ series: How to avoid a sudden increase in the size of the ibdata1 file

0. Introduction What is the ibdata1 file? ibdata1...