loading...

What's the order of execution?

318097 profile image Mehul Lakhanpal Originally published at codedrops.tech ・1 min read
setTimeout(() => console.log('1'), 0);

Promise.resolve().then(() => console.log('2'));

console.log('3');

Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Discussion

pic
Editor guide
Collapse
alexkhismatulin profile image
Alex Khismatulin

That's going to be 3, 2, 1. Why:
Start execution. Put setTimeout's callback into the task queue. Since a promise is already resolved, put then's callback into the microtask queue. Execute console.log('3');. Then we execute the microtask(then's callback) and its console.log(2); because microtasks are executed before regular tasks whenever the call stack empties. Then the task(setTimeout's callback) executed and console.log(1); in it.

Collapse
318097 profile image
Mehul Lakhanpal Author

Awesome 🔥😄