9. Event loop
- The event loop is the mastermind that orchestrates:
- What JavaScript code gets executed?
- When does it run?
- When do layout and style get updated?
- When do DOM changes get rendered?
- Responsible to pick up the task from Task queue or Micro task queue
and execute it in the callstack.
10. Event loop - pseudo code
while(true) {
task = eventLoop.nextTask();
// execute callback in the task queue
if (task) {
task.execute();
}
// execute all callbacks in the micro task queue
eventLoop.executeMicrotasks();
if (eventLoop.needsRendering()) {
eventLoop.render();
}
}
11. Execution strategy
- If one task contains multiple micro tasks, all the callbacks queued in
Micro task queue is executed first before picking up the next task
from the task queue.
- Before executing next task from the task queue, callstack should be
empty.
19. References
- What the heck is event loop anyway ?
- Jake Archibald: In The Loop - JSConf.Asia 2018
- Event loop explainer - and its pseudo code
- JavaScript: How is callback execution strategy for promises
different than DOM events callback?