Event Loop Flashcards
What is the event loop
The event loop manages the execution of code, handling events and asynchronous tasks.
At a high level, the event loop is a mechanism for handling and prioritizing code execution in JavaScript. When a script is executed in a browser or a Node.js environment, it runs on a single thread. This means that only one task can be executed at a time, and any blocking operation will prevent other tasks from being executed until the blocking operation is complete.
To avoid blocking, JavaScript uses an event loop to handle asynchronous operations. The event loop is essentially a loop that runs continuously and checks for tasks that are waiting to be executed. These tasks are added to a queue, and the event loop runs through the queue, executing each task in order.
What are the main components of the event loop?
- The call stack
- The event queue
- The heap
- Web APIs
- The micro-task queue
How does the event loop work?
Call Stack:
* When you execute a script, JavaScript starts by adding a function call to the call stack.
* The call stack is a data structure that keeps track of the functions that are currently being executed.
* Functions are processed via last-in first-out principle (LIFO)
Execution:
* Functions are executed in the order they appear in the call stack.
* If a function calls another function, the new function is added to the call stack.
Asynchronous Callbacks:
* When an asynchronous operation is initiated (e.g., fetching data, setTimeout), it is moved to the Web APIs environment (provided by the browser or Node.js).
* A callback function is associated with the asynchronous operation.
Event/Callback/Message Queue:
* Once the asynchronous operation is completed, the associated callback function is placed in the event queue. Uses first-in-first out principle
Job Queue
Apart from Callback Queue, browsers have introduced one more queue which is “Job Queue”, So when you use promises in your code, you add .then() method, which is a callback method. These thenable
methods are added to Job Queue once the promise has returned/resolved, and then gets executed. Also mutationObserver.
Event Loop:
* The event loop constantly checks if the call stack is empty.
* If the call stack is empty, it takes the first function in the Event/ Callback/ Message queue and pushes it onto the call stack, starting the execution of that function.
Callback Execution:
* The callback function is executed, and the process repeats.
Can you describe the process in phases?
Timer Phase: This phase handles setTimeout() and setInterval() functions, which add timed callbacks to the queue.
Pending Callback Phase: This phase handles callbacks that are generated by I/O operations, such as network requests or file system operations.
Idle, Prepare, and Poll Phases: These phases are responsible for waiting for events to occur, such as user input or other system events.
Check Phase: This phase handles setImmediate() functions, which add immediate callbacks to the queue.
Close Callbacks Phase: This phase handles callbacks that are generated by close events, such as when a server connection is closed.
What are WebAPIs and how do they work with the event loop?
Web APIs (Application Programming Interfaces) in the context of JavaScript typically refer to interfaces provided by web browsers to interact with various web-related functionalities. These APIs are part of the browser environment and allow JavaScript code to access features not directly available in the JavaScript language itself.
Can you name some common webApis?
- DOM (Document Object Model) (setTimeout, setInterval)
- XMLHttpRequest and Fetch API
- Web Storage API
- Canvas and WebGL
- more
How are promises handled by the event loop?
Promise creation: When a Promise is created, it enters a “pending” state. This means that the Promise is waiting for its asynchronous operation to complete.
Asynchronous operation: The code that follows the creation of the Promise performs some asynchronous operation, such as making an HTTP request or reading from a file. This operation runs in the background, allowing the rest of the code to continue running.
Event loop: While the asynchronous operation is running, the event loop is continuously checking the callback queue to see if any tasks are ready to be executed.
Promise resolution or rejection: Once the asynchronous operation is complete, the Promise enters either a “resolved” state (if the operation was successful) or a “rejected” state (if the operation failed). The Promise then receives a value or an error object.
Microtask queue: When a Promise is resolved or rejected, its handler functions are added to the microtask queue. This is important because microtasks are executed before any other tasks in the event loop, including callbacks from I/O operations.
Microtask execution: Once the microtask queue has been emptied, the event loop will begin to process any tasks in the callback queue.
What is the Microtask Queue in JavaScript?
The Microtask Queue, also known as the Job Queue, is a type of task queue in JavaScript that holds a list of microtasks. These tasks are scheduled to run after the currently executing script is complete and before the event loop continues with the next task in the task queue.
How does the Microtask Queue work?
After each task in the task queue, the event loop will process all the microtasks in the Microtask Queue before moving on to the next task. If a microtask adds more microtasks to the queue, those will also be processed before the next task starts.
What is an example of a microtask?
Microtasks include mutation observer callbacks and promise callbacks. When a promise is resolved or rejected, the callback function is not immediately executed; instead, it is added to the Microtask Queue to be processed as a microtask.
Why is the Microtask Queue important?
The Microtask Queue plays a crucial role in maintaining the asynchronous behavior of JavaScript. It allows short-duration tasks to be executed without significant delay, providing faster feedback to the user and a smoother user experience.
What is the heap and how is it used by the event loop?
The heap is an area of (mostly unstructured) memory.
How does event/message/callback queue work?
Message queue can process only one message at the time. What’s more, if message queue contains multiple messages each message has to be processed before any other message can. Processing of every message depends on the completion of the previous message. If one message takes more time to process other messages has to wait.
What happens to setTimeOut callbacks set to zero delay?
The idea is that the callback passed into this timeout should be executed immediately. The reality is that this might not happen.
As you know, message queue can process only one message at the time. Each message has to be completed before the queue can process another one. So, if you use setTimeout with delay set to 0 its callback will be executed immediately only if it is the first message in the message queue. Otherwise, it will have to wait.