๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐๐๐๐ป๐ฐ ๐๐ ๐ฝ๐น๐ฎ๐ถ๐ป๐ฒ๐ฑ ๐๐ถ๐ธ๐ฒ ๐ฎ ๐๐ฟ๐ผ๐ฐ๐ฒ๐ฟ๐ ๐ฆ๐๐ผ๐ฟ๐ฒ
Most people explain the JavaScript Event Loop using hard words. They talk about Web APIs and Microtask Queues. You memorize the words but you do not understand the concept.
Think of JavaScript as a grocery store with one cashier. The cashier serves one person at a time.
If you run these lines: console.log("A"); console.log("B"); console.log("C");
The output is A, B, then C. One task follows another.
Now imagine a customer asks the cashier to wait 5 seconds. If the cashier waits, the whole store stops. This is what happens if JavaScript handles timers alone.
Instead, JavaScript uses a helper.
When you use setTimeout, JavaScript tells the browser: "Watch this timer for me."
The browser takes the job. JavaScript continues to the next task immediately. After 5 seconds, the helper says the timer is done.
The browser cannot interrupt the cashier. It puts the task in a waiting line called the Callback Queue.
The Event Loop acts as a manager. The manager asks one question: "Is the cashier busy?"
If the cashier is busy, the manager waits. If the cashier is free, the manager takes the next person from the waiting line.
JavaScript has two waiting lines with different priority levels.
High Priority (Microtask Queue):
- Promise.then()
- queueMicrotask()
Low Priority (Macrotask Queue):
- setTimeout()
- setInterval()
- DOM events
The manager always clears the high priority line first. This is why a Promise runs before a setTimeout.
When you fetch data from a server, the browser handles the request. JavaScript does not sit idle. Once the data arrives, the task enters the queue. JavaScript runs it when it is ready.
If the cashier starts a task that takes 10 minutes, the store freezes. This happens when you run heavy math on the main thread. Web Workers solve this by hiring an extra cashier. The heavy work runs on a separate thread. This keeps the store moving.
Summary:
- JavaScript = Cashier
- Browser Web APIs = Helpers
- Callback Queue = Waiting Line
- Event Loop = Manager
- Web Workers = Extra Cashiers
Source: https://dev.to/aarthirs/-javascript-async-explained-like-a-grocery-store-4men