Javascript event loop expained
JavaScript runs on a single thread, meaning it can only do one thing at a time.
But why we need event loop?
without it we could not run functions asynchronously.
Gmeet without event loop
streamVideo(); // ← runs forever, blocks everything
receiveChat(); // ← never reached
detectSpeech(); // ← never reached
updateParticipants(); // ← never reached
So you won't be able to do anything except watching video theoretically.
The event loop is the mechanism that lets it appear to handle many things (timers, network calls, user events) without blocking.
The four key pieces
1. Call Stack This is where your code actually runs. Functions get pushed when called and popped when they return. Think of it as a stack of plates — last in, first out.
2. Web APIs (Browser / Node.js) These are off-thread helpers provided by the environment — not by JS itself. setTimeout, fetch, DOM event listeners all live here. JS hands them work and moves on immediately.
3. Microtask Queue For fast, high-priority callbacks — primarily Promise .then() handlers and queueMicrotask(). This queue is always drained completely before the event loop picks up anything from the callback queue.
4. Callback Queue (Macrotask queue) For lower-priority, slower callbacks — setTimeout, setInterval, DOM event handlers. One macrotask is picked per event loop "tick."
The golden rule
When the call stack is empty: drain all microtasks first, then pick one macrotask. Repeat forever.
That's why, "promise" logs before "timeout" — even though both were scheduled "at the same time." The Promise lives in the microtask queue (higher priority) while setTimeout lives in the macrotask queue.
console.log("start");
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("end");
// Output:
// start
// end
// promise ← microtask runs before macrotask
// timeout
This surprises most beginners! setTimeout(..., 0) doesn't mean "run immediately" — it means "run after the current synchronous code AND all microtasks are done."
Why stack did'nt gave reverse order.
The call stack is LIFO (Last In, First Out), but JavaScript executes your code one statement at a time. Each statement is pushed onto the stack, executed completely, and then popped before moving to the next statement.
Push console.log(start) -> Execute - >Pop



