About the Event Loop event loop

1. Event Loop concept:

Event Loop is an event loop, which refers to a browser or Node mechanism that solves the problem of non-blocking when javaScript runs single-threaded, that is, we often use the asynchronous principle.

二、Event Loop:

Synchronous tasks and asynchronous tasks
In order to prevent a time-consuming task from causing the program to freeze, javaScript divides the tasks to be executed into two categories:

  • 1. Synchronous tasks (syncchronous)
    are also called non-time-consuming tasks, which refer to those tasks that are queued for execution on the main thread.
    Only when the previous task is executed can the next task be executed.

  • 2. Asynchronous tasks (asyncchronous)
    Also known as time-consuming tasks, asynchronous tasks are entrusted by javaScript to the host environment for execution
    When the asynchronous task execution is completed, the javaScript main thread will be notified to execute the callback function of the asynchronous task

3. The execution process of synchronous tasks and asynchronous tasks:

insert image description here

	1.同步任务由JavaScript 主线程次序执行
	
	2.异步任务委托给宿主环境执行
	
    3.已完成的异步任务对应的回调函数,会被
	    加入到任务队列中等待执行
	    
	4.avaScript 主线程的执行栈被清空后,会
	   读取任务队列中的回调函数,次序执行
	   
	5.JavaScript 主线程不断重复上面的第 4 步

Macrotasks and Microtasks:

insert image description here

The fundamental difference between macrotasks and microtasks:

1. Common macro tasks are: setTimeout setInterval ajax DOM event

2. Common microtasks are: promise async/await

3. The execution time of microtasks is earlier than that of macrotasks

4. Micro tasks are specified by es6 syntax, and macro tasks are specified by browsers

Execution order of macrotasks and microtasks:

insert image description here

After each macrotask is executed, it will check whether there are still microtasks to be executed. If so, after executing all the microtasks, continue to execute the next macrotask

Classic Case:

console.log('start');
setTimeout(() => {
    
    
    console.log(1);
}); 
Promise.resolve('x').then(() => {
    
    
    console.log(2);
}).then(() => {
    
    
    console.log(3);
}).then(() => {
    
    
    console.log(4); 
})
console.log('end');

Input result: start–>end–>2—>3–>4–>1

analyze:

1. start and end belong to the priority execution of synchronous code

2. The code in promise also belongs to synchronous code, but the code in .then belongs to microtask in asynchronous code, which will be executed later

3. setTimeout belongs to the macro task in the asynchronous code, and is finally executed

Guess you like

Origin blog.csdn.net/m0_66504310/article/details/128139886