This content originally appeared on DEV Community and was authored by Dipak Ahirav
JavaScript is single-threaded, but it manages to handle asynchronous operations seamlessly. The magic behind this is the Event Loop. In this blog, we'll dive deep into how the Event Loop works and how JavaScript handles concurrency. 🧙♂️
please subscribe to my YouTube channel to support my channel and get more web development tutorials.
📜 Table of Contents
- Introduction
- Call Stack
- Web APIs
- Callback Queue
- Event Loop
- Microtasks and Macrotasks
- A Simple Example
- Conclusion
📚 Introduction
JavaScript’s concurrency model is based on an event loop, which allows it to perform tasks asynchronously, even though it runs on a single thread. This means it can handle many tasks at the same time without waiting for one to finish before starting another.
🏗️ Call Stack
The call stack is a simple data structure that keeps track of function calls. Think of it as a pile of books where you can only add or remove the book on top.
When a function is called, it’s added to the stack. When the function execution is complete, it’s removed from the stack.
function foo() {
console.log('foo');
}
function bar() {
foo();
console.log('bar');
}
bar();
- When
bar()
is called, it goes on top of the stack. - Inside
bar()
,foo()
is called, so it’s placed on top ofbar()
. - When
foo()
finishes, it’s removed from the stack, andbar()
continues.
🌐 Web APIs
JavaScript in browsers provides Web APIs for handling tasks like setTimeout
, fetch
, and DOM events. These APIs run in the background and, when tasks are completed, their callbacks are added to the Callback Queue.
🔃 Callback Queue
The Callback Queue (also known as the Task Queue) is where asynchronous callbacks from Web APIs wait to be executed.
When the call stack is empty, the Event Loop picks the first task from the Callback Queue and puts it on the call stack for execution.
🔄 Event Loop
The Event Loop is like a manager who keeps an eye on the call stack and the Callback Queue. Here’s how it works:
- The Event Loop looks at the call stack to see if it’s empty.
- If the stack is empty, it takes the first task from the Callback Queue and puts it on the stack.
- The task runs and is then removed from the stack.
- This process repeats.
🧩 Microtasks and Macrotasks
Tasks in JavaScript are divided into two categories: macrotasks and microtasks.
-
Macrotasks: These include
setTimeout
,setInterval
, and I/O operations. They are placed in the Callback Queue. -
Microtasks: These include
Promise
callbacks andMutationObserver
. They are placed in the Microtask Queue.
Microtasks have a higher priority than macrotasks. They are executed right after the current task completes, before any macrotasks.
👨💻 A Simple Example
Let’s look at an example to see this in action:
console.log('Start');
setTimeout(() => {
console.log('setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise');
}).then(() => {
console.log('Another Promise');
});
console.log('End');
Step-by-Step Execution:
-
console.log('Start')
is added to the stack and runs immediately, logging "Start". -
setTimeout
is called, which registers a task in the Web API to run after 0ms. Its callback is placed in the Callback Queue. -
Promise.resolve().then(...)
creates a microtask. The callback for this microtask is placed in the Microtask Queue. -
console.log('End')
is added to the stack and runs immediately, logging "End".
At this point, the stack is empty. The Event Loop checks the Microtask Queue first:
- The first promise callback runs, logging "Promise".
- The second promise callback runs, logging "Another Promise".
Finally, the Event Loop checks the Callback Queue:
- The
setTimeout
callback runs, logging "setTimeout".
Output:
Start
End
Promise
Another Promise
setTimeout
🏁 Conclusion
Understanding the Event Loop and Concurrency Model is essential for writing efficient JavaScript code. By mastering these concepts, you can handle asynchronous operations better and build more responsive applications. 🌟
🚀 Happy Coding!
Feel free to leave your comments or questions below. If you found this guide helpful, please share it with your peers and follow me for more web development tutorials. Happy coding!
Follow and Subscribe:
- Instagram: devdivewithdipak
- Website: Dipak Ahirav
- Email: dipaksahirav@gmail.com
- YouTube: devDive with Dipak
- LinkedIn: Dipak Ahirav
This content originally appeared on DEV Community and was authored by Dipak Ahirav
Dipak Ahirav | Sciencx (2024-06-20T02:18:25+00:00) 🕒 Understanding the Event Loop and Concurrency Model in JavaScript. Retrieved from https://www.scien.cx/2024/06/20/%f0%9f%95%92-understanding-the-event-loop-and-concurrency-model-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.