Event Loop
What is Event Driven Programming
Event-driven programming is a programming paradigm where the flow of a program is determined by external "events" like user actions (mouse clicks, key presses), system notifications, or sensor inputs, meaning the program reacts and executes code only when a specific event occurs, rather than following a linear sequence of instructions.
Micro and Macro Task Queue
Micro-task Queue
Has higher priority than the Macro-task queue
- Holds
Promises
andAsync
functions
Promise async function
Macro-task Queue (ref. as Task queue or Callback queue)
Runs when microtask queue is empty
- Macro task moves into the Call stack
Browser APIs UI rendering `.then()` Callback functions after async/Promise
setTimeout() setInterval() setImmediate()
Event Loop Process
Event loop is something that constantly runs to handle functions across the tasks.
- One go-around of event loop will have exactly one task processed from macrotask queue
Check the Macrotask queue
- If the function is asynchronous, it is sent to the API module
- Module pushes these tasks to macro-task queue after specified time
- When added to macro-task, it must wait for the next cycle of Event loop to be evaluated
After that original macrotask completes, all available microtasks are processed
- microtask can queue even more microtasks
- when microtasks keep running and doesn't clear, it can lead to blocking fo UI rendering
In next cycle, function is passed to the Call stack
- Call stack executes the function
- When everything is empty, event loop waits for the next function to be added to the Call stack