DEV Community

Mohsen Fallahnejad
Mohsen Fallahnejad

Posted on

JavaScript's Event Loop

The event loop lets JavaScript handle async tasks on a single thread.

Example Code

console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 
Enter fullscreen mode Exit fullscreen mode

Output: Start → End → Promise → Timeout


Why this order?

  • Start and End are synchronous → run immediately on the call stack.
  • Promise.then is a microtask → runs before macrotasks.
  • setTimeout callback is a macrotask → runs after microtasks drain.

Originally published on: Bitlyst

Top comments (0)