Read an article to understand what is Event Loop

Event Loop is a computer program execution model for handling asynchronous events and writing non-blocking code, which occupies an extremely important position in modern web development. This article will give an in-depth introduction to the working principle, task classification and application scenarios of Event Loop to help readers understand this concept more comprehensively and deeply.

1. Working principle

  1. JavaScript is a single-threaded language that can only handle one task at a time while executing code. If the tasks executed in the JS script are blocked or take a long time, it will cause the entire page to become slow or unresponsive. In order to solve this problem, Event Loop came into being.
  2. The working logic of Event Loop is very simple: continuously execute code and process events in the main thread, and wait for the arrival of events if there is no current event to be processed. All events are placed in a first-in-first-out queue, and are processed one by one by the Event Loop at the next tick. Each tick is divided into two types of tasks: macro tasks and micro tasks.
    • Macro tasks are added to the end of the event queue through setTimeout, setInterval, script (overall code), I/O, etc.;
    • Microtasks are added to the head of the event queue by Promise.then(), process.nextTick, Object.observe, etc.;
  3. Before each macrotask is executed, all queued microtasks are executed first. Similarly, a macrotask may contain multiple microtasks. This task queue management method ensures the execution order of asynchronous tasks, and also ensures that the main thread can perform other tasks without being blocked.

2. Task classification

The macrotask and microtask have been briefly introduced before, and the two will be explained in detail below.

2.1 Macro task

Common macro tasks include setTimeout/setInterval, I/O and event waiting. Macro tasks in JavaScript are executed based on the "event-driven" mode. For example:

console.log('1');

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

console.log('3');

In this example, the first line prints '1', then adds a timer event, then outputs '3', and finally the callback function of the timer event outputs '2'. Since the time of the timer is 0 milliseconds, it does not actually wait for any time, but adds the callback function to the macro task queue and starts executing it at the next tick (the end of the giant screen queue).

2.2 Microtasks

A microtask is a group of small tasks in a macrotask whose results can be dominated by the macrotask. They must be executed before the end of the current tick, otherwise they may not be executed normally in the next tick. Common microtasks include Promise.then(), Process.nextTick Node.js-specific API and Object.observe.

It should be noted that microtasks generated within the same macrotask will be executed before the next macrotask . For example:

console.log('1');

setTimeout(function () {
    
    
  console.log('2');
  Promise.resolve().then(function () {
    
    
    console.log('3');
  });
}, 0);

Promise.resolve().then(function () {
    
    
  console.log('4');
});

console.log('5');

The output results are: 1, 5, 4, 2, 3. The parsing process is as follows:

  1. the first tick
    • First print out '1', then execute the Promise.then() microtask, and add a task that outputs '4' at the head of the microtask queue.
    • Now there is only one timer event in the macro task queue, which is assigned to the next tick for execution.
  2. the second tick
    • Start executing the timer event, output '2'.
    • Then, a Promise.then() is generated in the timer event, and it is added to the microtask queue of the current round.
    • After all the macro tasks of the current round are executed, start processing the micro task queue of the current round, output '4', and then output '3'.
  3. So the output result is 1, 5, 4, 2, 3.

3. Application scenarios

  1. Event Loop is often used in web development to handle asynchronous programming. For example, an asynchronous Ajax request needs to be used when obtaining data from the server, otherwise it will cause the page to wait for too long, the user experience is poor, and the browser may crash. The existence of Event Loop can make it easier for front-end engineers to manage these asynchronous tasks.

  2. Event Loop is also widely used in Node.js to handle I/O operations. Node.js provides a variety of API interfaces, such as fs, net or http modules, which implement asynchronous operations based on callback functions and avoid blocking the main thread.

  • In short, whether it is front-end development, back-end development or mobile development, Event Loop plays a vital role. Learning to master Event Loop is very helpful for you to achieve efficient and smooth asynchronous computing and optimize performance.

4. Examples

Here are some code samples to illustrate how the Event Loop works:

  1. Execution order example of macrotasks and microtasks
// 同步任务,输出 '1'
console.log('1');

setTimeout(() => {
    
    
  // 定时器回调函数,宏任务
  console.log('2 - Macro Task');
  // 添加一个微任务到队列中
  Promise.resolve().then(() => console.log('3 - Micro Task'));
}, 0);
// 添加一个微任务到队列中
Promise.resolve().then(() => console.log('4 - Micro Task'));
// 同步任务,输出 '5'
console.log('5');

The output of the above code is:

1
5
4 - Micro Task
2 - Macro Task
3 - Micro Task

The explanation is as follows:

  • output '1' first
  • Add setTimeout callback function to the macro task queue.
  • Add the callback function of the first Promise (for microtasks) to the microtask queue.
  • output '5'
  • Execute the first task in the microtask queue and output '4 - Micro Task'
  • Start to execute the macro task queue, execute the setTimeout callback function at the head of the queue, and output '2 - Macro Task'. Then add the Promise callback function to the microtask queue
  • Execute the first task in the microtask queue and output '3 - Micro Task'
  1. Using Event Loop in Node.js:
const fs = require('fs');

console.log('Start reading a file...'); // 同步输出提示信息

fs.readFile('file.md', 'utf-8', (err, content) => {
    
     // 异步读取文件内容
  if (err) {
    
    
    console.log('Error:', err); // 如果报错打印错误信息
    return;
  }

  console.log(content); // 异步输出文件内容
});

console.log('Carry on executing...'); // 同步输出提示信息
  • In the above code, Node.js provides the method readFile to read files asynchronously through the fs module. The entire process of reading files is asynchronous and non-blocking. The program will execute the output 'Carry on executing...' immediately after executing readFile, and then wait until the readFile task is completed, the Event Loop will detect and execute the callback function, and output the read file content.

  • To sum up, Event Loop is widely used in asynchronous programming and I/O models, and is an indispensable part of Web development.

Guess you like

Origin blog.csdn.net/weixin_41636483/article/details/130227971