Event Loops 🔄

Event Loops 🔄
Before diving into Event Loops, it's crucial to first understand how the Call Stack operates. The Call Stack's role is to push incoming tasks onto the stack and pop them off in the order they arrived, ensuring tasks are handled sequentially.

Event Loop & Call Stack Coordination:
The Event Loop coordinates with the Call Stack to manage the task queue, ensuring the first item in the queue is processed when the stack is ready. Each user interaction, like a click event, is added to the Call Stack and waits in the queue. This can sometimes result in lag when a user spams an event, like repeatedly clicking a button.

❓ So, what exactly happens during an event?
When a user interacts with a function in the browser, that function is queued in the Call Stack. It patiently waits for its turn and then executes its tasks, which may include calling web APIs if necessary. 

Once complete, the function either **ends** or re-enters the queue for further processing, depending on the specific instructions given. Asynchronous functions (like those using `setTimeout`) don't execute immediately; they wait until the Call Stack is clear before running. This coordination ensures that JavaScript renders smoothly in the browser, with the asynchronous code remaining in the queue until it's ready to execute.

⏳ `setTimeout(0)`: What does this do?
The `setTimeout(0)` function places a task in the queue but doesn't execute it immediately. Even though the delay is set to 0 milliseconds, it still has to wait until the current stack is clear and it's the function's turn in the queue. This brief delay allows the browser to handle other critical rendering and processing tasks already in line. It's important to note that JavaScript doesn't prioritize a 0 millisecond delay over other tasks—it simply indicates the minimum wait time before the function can execute.

Published: Sept 2024

← Back to Blog