Event Loop, Call Stack, Callback Queue, Event Table, Mapping, Microtask
Sraban Pahadasingh June 24, 2024 10:38 PM1.Event Loop
The Event Loop is a fundamental concept in JavaScript that enables asynchronous programming. It allows non-blocking operations to be executed in a single-threaded environment, managing the execution of multiple operations over time.
- How It Works: The Event Loop constantly checks the Call Stack to see if it's empty. If it is, it pushes the first callback from the Callback Queue (or Microtask Queue) onto the Call Stack to be executed.
2.Call Stack
The Call Stack is a data structure that keeps track of function calls. When a function is called, it is pushed onto the stack, and when the function completes, it is popped off the stack.
- Example:
function greet() {
console.log('Hello');
}
function sayGoodbye() {
console.log('Goodbye');
}
greet(); // Pushed onto the Call Stack
sayGoodbye(); // Pushed onto the Call Stack after greet() completes
3.Callback Queue
The Callback Queue (or Task Queue) is a queue where callback functions are stored after being moved from the Event Table (or task scheduler).
- Example:
setTimeout(() => {
console.log('This is a callback');
}, 1000);
4.Event Table
The Event Table is a data structure that keeps track of events and their associated callback functions. When an event occurs, the corresponding callback function is moved to the Callback Queue.
- Example:
document.addEventListener('click', () => {
console.log('Document clicked');
});
5.Microtasks
Microtasks are similar to tasks in the Callback Queue but have higher priority. Microtasks include operations like Promise
callbacks and MutationObserver
callbacks.
- Example:
Promise.resolve().then(() => {
console.log('Microtask');
});
6.Mapping
Mapping in the context of the event loop refers to how the execution context is transferred between the different structures (like the Call Stack and Callback Queue) based on the Event Loop's management.
Summary:
The Order of execution as follows
Call Stack(functions) --> Job Queue(promises, mutationObserver) ---> Callable Queue(setTimeout(), ....)
Reference: Event Looping in JS