DEV Community

loading...
Cover image for JavaScript Interview Question #35: What is faster, zero timeout, or immediate resolve?

JavaScript Interview Question #35: What is faster, zero timeout, or immediate resolve?

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・1 min read

js-test-35

What's the order of the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Both setTimeout and Promise.resolve are asynchronous actions, which means that the inner console.log statements will be evaluated after some delay.

The difference is that Promise.resolve schedules the microtask, and setTimeout schedules the macrotask. Micro tasks have higher priority than macrotasks, thus Promise.resolve will be evaluated faster and the first output will be 2.


ANSWER: 2 will be printed on the first line, followed by 1.

Learn Full-Stack JavaScript

Discussion (5)

pic
Editor guide
Collapse
omrisama profile image
Omri Gabay

Never heard of this concept of microtasks vs macrotasks. Where can I read more about it?

Collapse
paramagicdev profile image
Konnor Rogers

This is the best read I've found on tasks.

jakearchibald.com/2015/tasks-micro...

Collapse
jolok profile image
Joshua

Frontend Masters has a course taught by Will Sentance -- he explains this in painstaking detail. Very good course -- I think it's 'Javascript, the Hard Parts'.

Collapse
paramagicdev profile image
Konnor Rogers

FWIW, this answer can also be browser dependent. Apparently each browser implements tasks slightly differently so in certain browsers and browser versions, the answer may not always be the same.

jakearchibald.com/2015/tasks-micro...

Collapse
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Nice blog.

I am also curious on how to manage blogging with JavaScript enabled? MDX?