JavaScript is single-threaded, meaning it executes one task at a time. The event loop is the mechanism that manages asynchronous operations by coordinating the call stack and task queues. When async tasks (like setTimeout
, Promises, or async/await) are executed, they’re scheduled in either the macrotask queue (e.g., setTimeout
, setInterval
) or the microtask queue (e.g., Promises, queueMicrotask
). The event loop first clears the call stack, then processes all microtasks before moving to the next macrotask. Understanding this helps developers write non-blocking, efficient code and avoid common async pitfalls.
Working with the Event loop and Async in JavaScript
It prints messages to the console in a specific order using:
- Normal code (runs immediately)
setTimeout
(delayed)Promise.then
(microtask)queueMicrotask
(another microtask)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>JavaScript Event Loop Example</title> </head> <body> <script> console.log('1. Script start'); setTimeout(() => { console.log('5. setTimeout (Macrotask)'); }, 0); Promise.resolve().then(() => { console.log('3. Promise.then (Microtask)'); }); queueMicrotask(() => { console.log('4. queueMicrotask (Microtask)'); }); console.log('2. Script end'); </script> </body> </html>
Output:
1. Script start 2. Script end 3. Promise.then (Microtask) 4. queueMicrotask (Microtask) 5. setTimeout (Macrotask)