Event Loop
JavaScript is a single-threaded language, meaning it executes one task at a time. The Event Loop enables JavaScript to handle asynchronous operations efficiently by managing the execution of callbacks without blocking the main thread. It is not a specific piece of JavaScript code but a runtime mechanism for scheduling tasks.
Working of the Event Loop
Function calls form a call stack, where each function execution is pushed and popped in a Last In, First Out (LIFO) manner. Objects are allocated in the heap, a large, unstructured memory region. The JavaScript engine processes functions until the call stack is empty, after which the event loop begins processing tasks from various queues.
The event loop executes code in the following order:
- Synchronous code (executed immediately in the call stack).
- Microtasks (e.g.,
Promise.then()
,MutationObserver
- executed before rendering updates). - Macrotasks (e.g.,
setTimeout
,setInterval
,setImmediate
, I/O tasks - executed after microtasks).
Each type of task has its own queue, ensuring efficient scheduling and execution.
Example
The example below shows that even though the code appears to execute sequentially, synchronous console logs will run first. The Promise
callback, which is an asynchronous microtask, will execute only after all synchronous code has finished running:
console.log('Start');Promise.resolve().then(() => {console.log('Promise callback comes after');});console.log('End');
The code above generates:
StartEndPromise callback comes after
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Skill path
Create a Back-End App with JavaScript
Learn how to build back-end web APIs using Express.js, Node.js, SQL, and a Node.js-SQLite database library.Includes 8 CoursesWith CertificateBeginner Friendly30 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours