Understanding the JavaScript Event Loop (Made Simple)
The JavaScript event loop is what makes asynchronous programming in JavaScript possible. Here's a simple explanation!
π§ Key Concepts
1. Single-Threaded
JavaScript can only do one thing at a time because itβs single-threaded.
console.log("Task 1");
console.log("Task 2");
π Output:
Task 1
Task 2
2. Synchronous vs. Asynchronous
- Synchronous tasks: Run in order, one after another.
- Asynchronous tasks: Don't block the main thread; they wait until they're ready to run.
console.log("Start");
setTimeout(() => {
console.log("Async Task");
}, 1000);
console.log("End");
π Output:
Start
End
Async Task
π How the Event Loop Works
-
Call Stack
- The place where tasks are executed one by one.
- When a function runs, it gets added to the stack. When it finishes, it gets removed.
-
Web APIs
- Asynchronous tasks (like
setTimeout
) are handled here. They wait in the background.
- Asynchronous tasks (like
-
Callback Queue
- Once the asynchronous task finishes, its callback is added to the queue.
-
Event Loop
- The event loop checks:
- Is the call stack empty?
- If YES, it takes tasks from the callback queue and pushes them to the stack.
- The event loop checks:
β¨ Example: Step-by-Step
console.log("Start");
setTimeout(() => {
console.log("Timeout Task");
}, 2000);
console.log("End");
1οΈβ£ Call Stack
Step | Call Stack | Notes |
---|---|---|
1 | console.log |
Logs "Start" |
2 | setTimeout |
Registers timeout task |
3 | console.log |
Logs "End" |
2οΈβ£ Web APIs
-
setTimeout
moves to Web APIs and starts the timer.
3οΈβ£ Callback Queue
- After 2000ms, the callback (
() => console.log("Timeout Task")
) moves to the queue.
4οΈβ£ Event Loop
- The event loop checks if the call stack is empty.
- The callback is moved to the stack and executed.
π Final Output:
Start
End
Timeout Task
π Visualizing the Event Loop
To truly understand the event loop, check out these resources:
Happy coding! π
Top comments (0)