Some simple personal insights into eventLoop
Event loop is divided into macro tasks and micro tasks, and is a single thread
Macro task: it is by the host (node, the browser) initiate script, settimeout and setInterval…
Microtasks: these are initiated by the javascript engine and generated by code, i.e. only promise’s then and process.nexktick
Execution order
1. Execute the synchronization code in scrpTE in macro task first
2. After the synchronous code is executed, execute macro and micro tasks in the asynchronous code. Micro tasks take precedence over macro tasks, that is, then and nextick should be executed before setTimeout
3. After the microtasks are executed, execute the macro tasks in the asynchronous layer. If the macro tasks in the asynchronous layer still have microtasks, continue to execute the microtasks in the asynchronous layer
4. If process.nextTick is in the asynchronous queue, it will be executed first, which can be considered prior to promise
A simple summary is: after the synchronization task is finished, the micro task should be dealt with first, then the macro task should be dealt with, and the internal processing of the macro task should repeat the above actions.
console.log('start'); setTimeout(() => { console.log('s1'); new Promise(resolve => { console.log('p2'); resolve(true); }).then(() => { console.log('then2'); }); }); function task() { console.log('task'); } new Promise(resolve => { console.log('p1'); resolve(true); }).then(() => { console.log('then'); }); task(); console.log('end'); Execution sequence: start P1 task end (synchronous task) then (micro task) S1 (macro task) P2 then2(macro task) Settimeout (()=>{console.log("1")},2000) setTimeout (()=>{console.log("2")},1000) Two seconds later, two is faster than oneCopy the code