JavaScript Event Loop: Non-Blocking Asynchronous Execution
The JavaScript event loop manages asynchronous operations by executing callbacks from a queue when the call stack is empty, preventing thread blocking.
Loop. Control structure repeating code until condition is met. Generated ELI5 content
graph LR
Center["JavaScript Event Loop: Non-Blocking Asynchronous Execution"]:::main
Pre_variable["variable"]:::pre --> Center
click Pre_variable "/terms/variable"
Rel_iteration["iteration"]:::related -.-> Center
click Rel_iteration "/terms/iteration"
Rel_recursion["recursion"]:::related -.-> Center
click Rel_recursion "/terms/recursion"
Rel_closed_loop_life_support["closed-loop-life-support"]:::related -.-> Center
click Rel_closed_loop_life_support "/terms/closed-loop-life-support"
classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
linkStyle default stroke:#4b5563,stroke-width:2px;
🧒 Explain Like I'm 5
Think of [JavaScript](/en/terms/javascript) as a chef who can only do one thing at a time. If they need to bake a cake (a long task), they don't just stand and wait for it. They put the cake in the oven and set a timer, then immediately start preparing a salad (another task). When the oven timer rings, the chef finishes the salad, takes out the cake, and then moves on. The [event loop](/en/terms/event-loop) is like the chef's system for managing these 'waiting' tasks, ensuring they get handled when ready without stopping other work.
🤓 Expert Deep Dive
The JavaScript event loop is a concurrency model that orchestrates the execution of code, tasks, and events. It continuously monitors the call stack and the task queue(s). Synchronous code is executed directly on the call stack. Asynchronous operations (e.g., setTimeout, Promises, I/O) are handed off to the host environment's APIs, which manage their execution. Once an asynchronous operation completes, its callback (or a Promise's fulfillment handler) is placed into a corresponding queue – the task queue (for macrotasks like setTimeout, DOM events) or the microtask queue (for microtasks like Promises, queueMicrotask). The event loop's core function is to, when the call stack is empty, dequeue tasks and execute them. Microtasks are generally processed before macrotasks. Specifically, after the current macrotask finishes and before the next macrotask begins, the event loop will execute all available microtasks. This prioritizes immediate callbacks (like Promise resolutions) over deferred ones, ensuring responsiveness and efficient handling of asynchronous operations across different JavaScript environments.