The premise
- Js runs in a single thread
- Asynchrony is implemented based on callbacks
- The Event loop is how asynchronous callbacks are implemented
The event loop process
- Synchronize the code line by line in the Call Stack
- When encountering asynchronous code, record it and wait for the opportunity (timing, network request)
- Time is up, move to the CallBack Queue
- If the Call Stack is empty, the Event Loop starts working
- The CallBack Queue is queried and moved to the Call Stack if any exists
- And then we continue our search
DOM events and Event loops
- Js is single threaded
- Asynchronous (setTimeout, Ajax) uses callbacks, based on event loops
- DOM events also use callbacks, based on event loops
Macro and micro tasks
MacroTask microTask
Macro tasks: setTimeout, setInterval, Ajax, DOM event microtasks: Promise, async/await microtasks are executed earlier than macro tasks
All asynchronous front-end (macro/micro)
Event loop and DOM rendering
Review, Event loop
- Js is single threaded and shares a thread with DOM rendering
- When js is executed, leave some time for DOM rendering
Call Stack idle (synchronous code completed) == “DOM render attempt ==” trigger Event loop
The difference between microtasks and macro tasks
- Macro task: triggered after DOM rendering, as specified by setTimeout browser
- Microtasks: Trigger before DOM rendering, as promised in ES6