JavaScript Event Loop Explained

Can you guess the output? 🤔 (JavaScript — no cheating) Take a second and think… 👇 👇 Output: A D C B Why does this happen? Because of the Event Loop. JavaScript first runs all synchronous code. Once the call stack is empty, the Event Loop: - executes all microtasks (Promises) - then moves to the macrotask queue (timers) That’s why Promise callbacks run before setTimeout, even with 0ms. Once the Event Loop clicks, async JavaScript finally starts making sense. Did you guess it right? 😄 #javascript #js #eventloop #async #frontend

  • No alternative text description for this image

Before this post I was worried about async, sync. I used to use async await but I don't know the reason why I used this but after this post I read comments and learned from GPT. And now I am clear. Sync code runs but it waits for previous code completions. It uses stack memory where code is execution. When async code runs it doesn't block code it allows the next code to run and in the background it runs and waits for results after results it shows. It uses queue memory for Wait the result after finishing stack queue will run and push the results in stack and stack run again. Now let's talking about Abcd Log A log Log D run first because it sync Log C mircrotask async but it priority high then this Log B macrotask async it priority less than mircrotask.

ADCB Because of event loop. setTimeout callback is registered in the callback queue and promises are registered in the microtask queue. Microtask queue has higher priority than callback queue. That's why C logged before B.

JavaScript runs synchronously first. So A and D are logged immediately. Then the event loop runs microtasks before macrotasks. Promise.then() is a microtask, so C executes next. setTimeout is a macrotask, so B runs last. Final output: A → D → C → B

this example clearly shows us the understanding of async and sync and macrotask and microtask natural of JS. first print A, D then C , then B hence -> A, D (sync) C -> microtask B -> macrotask

Thanks to Akshay saini, I can guess the right answer

I'll give you an even better one. This was asked in a real interview too. console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")).then(() => { setTimeout(() => console.log("D"), 0); console.log("E"); }); console.log("F");

ADCB. Normal logs then Promises then setTimeout. microtask queue vs macrotask queue.

Like
Reply

A D C B Why D because promises are handled by microtask queue and setTimeout are handled by callback queue. Microtask queues are prioritised here by the event loop.

See more comments

To view or add a comment, sign in

Explore content categories