Table of contents
What is the result of executing this code?
event loop
The main thread reads execution events from the "task queue". This process is cyclic. This mechanism is called an event loop.
(The running mechanism of JS is the event loop!)
Steps
Main thread task——>Micro task——>Macro task If there are still micro tasks in the macro task, continue to execute the micro tasks in the macro task. If the macro task Among the microtasks, there are also macrotasks that are being carried out in sequence
Synchronous tasks have no priority. Asynchronous execution has priority. Micro tasks (microtask queue) are executed first, and then macros are executed. Tasks (macro taskqueue), in order at the same level (micro tasks first, then macro tasks)
Concept explanation
main thread
All synchronous tasks are executed in the main thread, and asynchronous tasks may be executed in
macrotask
ormicrotask
micro task
- promise
- async
- await
- process.nextTick(node)
- mutationObserver (html5 new feature)
macro task
- script(whole code)
- setTimeout
- setInterval
- setImmediate
- I/O
- UI rendering
Event Loop classic example
What is the result of executing this code?
console.log('1') setTimeout(function callback(){ console.log('2') }, 1000) new Promise((resolve, reject) => { console.log('3') resolve() }) .then(res => { console.log('4'); }) console.log('5')
correct answer:
1,3,5,2,4
specific process:
Reference article:
The event loop mechanism (event loop) that can be understood at a glance - Nuggets (juejin.cn)
What exactly is Event Loop? Then let’s learn about the operating mechanism of JavaScript in the browser and Node environment respectively - CSDN Blog