๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐๐๐๐ป๐ฐ ๐๐ ๐ฝ๐น๐ฎ๐ถ๐ป๐ฒ๐ฑ ๐๐ถ๐ธ๐ฒ ๐ฎ ๐๐ฟ๐ผ๐ฐ๐ฒ๐ฟ๐ ๐ฆ๐๐ผ๐ฟ๐ฒ
Many developers memorize technical definitions about the Event Loop. They talk about Web APIs and Microtask Queues. They learn the words but do not understand the logic.
Think of JavaScript as a grocery store with one cashier. The cashier serves one customer at a time. This is how JavaScript works.
If you run code like this: 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. No one else gets served. 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 moves to the next task immediately.
After the timer ends, the helper cannot interrupt the cashier. The helper places the task in a waiting line called the Callback Queue.
The Event Loop acts as a manager. The manager asks: "Is the cashier busy?"
- If the cashier is busy, the manager waits.
- If the cashier is free, the manager pulls the next task from the waiting line.
JavaScript uses two waiting lines. One line has high priority.
- High priority: Promise.then() and queueMicrotask()
- Low priority: setTimeout() and setInterval()
The manager always clears the high priority line first. This is why a Promise runs before a setTimeout.
Network requests work the same way. When you fetch data, the browser handles the request. JavaScript does not sit idle. When the data arrives, the task enters the queue. JavaScript runs it when it finishes current tasks.
If the cashier starts a task that takes 10 minutes, the store freezes. This happens when you run heavy calculations on the main thread. Web Workers fix this. They hire an extra cashier to handle heavy work on a separate thread.
Here is the summary:
โข JavaScript = The Cashier โข Browser Web APIs = The Helpers โข Callback Queue = The Waiting Line โข Event Loop = The Manager โข Web Workers = Extra Cashiers
Stop memorizing definitions. Start visualizing the process.
Source: https://dev.to/aarthirs/-javascript-async-explained-like-a-grocery-store-4men