- Courses
- đ»Programming Languages
- đJavaScript
- Asynchronous JavaScript
- Event Loop
On this page
The JavaScript Event Loop
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
JavaScript is a single-threaded language, which means it has one Call Stack and can execute only one piece of code at a time. In a synchronous environment, a long-running script would "block" the thread, causing the browser to become unresponsive. The Event Loop is the specialized mechanism that allows JavaScript to perform non-blocking, asynchronous operations by offloading tasks to the browser environment and coordinating their execution.
The Architectural Componentsâ
To understand how concurrency works, you must visualize the four primary components of the JavaScript runtime environment: the Call Stack, Web APIs, the Task Queue, and the Event Loop itself.
The Call Stackâ
The Call Stack follows a LIFO (Last In, First Out) structure. When a function is invoked, it is "pushed" onto the stack. When the function returns a value or finishes executing, it is "popped" off the stack. If the stack is busy, JavaScript cannot do anything else.
Web APIs (Browser Environment)â
While the JavaScript engine (like V8) is single-threaded, the browser is not. Browsers provide Web APIs (such as setTimeout, DOM events, and fetch) that run in the background. When you call an asynchronous function, JavaScript hands the task over to these APIs and moves on to the next line of code in the stack.
The Task Queue (Callback Queue)â
Once a Web API finishes its task (e.g., a timer expires), it does not push the result back to the Call Stack immediately. Instead, it sends the callback function to the Task Queue. This is a "waiting room" for code that is ready to be executed.
The Event Loopâ
The Event Loop is a constant process that monitors both the Call Stack and the Task Queue. Its job is simple but vital: If the Call Stack is empty, the Event Loop takes the first task from the Task Queue and pushes it onto the stack for execution.
The Execution Workflowâ
The coordination between these components follows a strict sequence. Consider the following example:
console.log("Start");
setTimeout(() => {
console.log("Async Task");
}, 0);
console.log("End");
Despite the timer being set to 0 milliseconds, the output will be:
StartEndAsync Task
Step-by-Step Analysisâ
console.log("Start")is pushed onto the stack, executed, and popped off.setTimeoutis pushed onto the stack. The JavaScript engine recognizes this as a Web API task and hands the timer to the browser.setTimeoutis then popped off the stack.- The browser waits
0ms. Once finished, it moves the anonymous function() => { console.log("Async Task") }into the Task Queue. - While the browser was handling the timer, the engine immediately moved to
console.log("End"), pushed it to the stack, executed it, and popped it. - Now the Call Stack is empty. The Event Loop notices this and checks the Task Queue.
- The Event Loop moves the
Async Taskfunction from the queue to the Call Stack, where it is finally executed.
Macro-tasks vs. Micro-tasksâ
In modern JavaScript, the Task Queue is subdivided to prioritize certain types of operations. Understanding this distinction is essential for predicting the order of execution in complex applications.
Macro-tasksâ
These include standard asynchronous operations like setTimeout, setInterval, and I/O tasks. The Event Loop processes one macro-task per loop iteration.
Micro-tasksâ
These primarily include Promises (the .then/catch/finally handlers) and queueMicrotask. Micro-tasks have a higher priority than macro-tasks. The Event Loop will execute all pending micro-tasks in the micro-task queue before moving on to the next macro-task.
Blocking the Event Loopâ
Because the Event Loop can only push tasks when the stack is empty, performing heavy calculations (like processing a massive loop) will "starve" the Event Loop. If the stack never clears, the Event Loop can never pull tasks from the queue, resulting in a "frozen" user interface.
Professional Implementation Ruleâ
Never perform CPU-intensive synchronous work on the main thread. If a task is heavy, break it into smaller asynchronous chunks or utilize Web Workers to keep the Call Stack clear and the Event Loop flowing.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Asynchronous JavaScript
Next
Callbacks
-
The Architectural Components
- The Call Stack
- Web APIs (Browser Environment)
- The Task Queue (Callback Queue)
- The Event Loop
-
The Execution Workflow
- Step-by-Step Analysis
-
Macro-tasks vs. Micro-tasks
- Macro-tasks
- Micro-tasks
-
Blocking the Event Loop
- Professional Implementation Rule
