Event Loop
The JS monitor process determines the order in which different event are executed. This is the Event Loop
Basic knowledge of JS
JS is a sigle line scripting language. So it avoids the paradoxical problem of working with the same DOM at the same time.
The monitor process will constantly check if the main thread execution stack is empty. and if it is, it will go to the Event Queue to check if there are any functions waiting to be called.
All synchronized tasked are executed on the main thread, forming an execution stack.
Synchronous
Tasks queued for execution on the main thread which must wait the previous task to complete.
Asynchronous
Tasks enter the task queue but don’t enter the main thread cannot enter the main thread until the task queue notifies the main thread that an asynchronous task is ready.
- setTimeout
- setInterval
- ajax
- promise
- I/O
Micro Task
- promise.then
- promise.nextTick (node)
- Macro Task
- The overall script
- setTimeout
- setInterval
Event Loop
- With the overall scripty as the first macro task starting, splite the all task into two parts. Synchronous tasks and asynchronous tasks.
- Synchronous tasks will be executed enter the main thread right now.
- Asynchronous tasks will splite into micro and macro tasks.
- Macro and micro tasks will enter the different Event Table, and moves the registered callback function for the specified event to different event queue.
- When the main thread is idle, it will executed the callback functions in the Event Queue of microtask and the macro task in order.
Code
Case 1
1 | const event1 = () => { |
Micro | Macro | Output |
---|---|---|
5 | 2,9 | 1,4,10 |
2,9,8 | 1,4,10,5,6,7 | |
3 | 9,8 | 1,4,10,5,6,7,2 |
8 | 1,4,10,5,6,7,2,3,9 | |
1,4,10,5,6,7,2,3,9,8 |
Case 2
1 | const event2 = () => { |
Case 3
1 | const event3 = () => { |