Skip to main content

Command Palette

Search for a command to run...

Promise VS setTimeout() in Javascript.

Updated
3 min read
Promise VS setTimeout() in Javascript.
P

Prathmesh Dhatrak's Blogs

The other day I was talking to one of my seniors and he asked me is your JavaScript strong and do I understand how javascript works under the hood. So I was confident that I had watched the Philip Roberts "JSConf" video (which BTW is very awesome video) so that's why I said I have a strong understanding of javascript you can ask me questions. So then he asked my simple (I thought then) Promise and setTimeout() question, that was.

What will execute faster: an resolved promise callback or a "0sec" setTimeout() ?

setTimeout(function tO() {
  console.log('setTimeout function called');
}, 0);
Promise.resolve(true).then(function rS() {
  console.log('Promise Resolved function called');
});

So I tried to answer this question with the knowledge that I had. image.png

  • So first the setTimeout will be called in the call stack after the main execution contest is added.
  • Then as the setTimeout will execute through web API asynchronously.
  • So the javascript engine will get the Promise into the call stack.
  • And again the web API will execute the Promise asynchronously.
  • So at this movement, the setTimeout with 0 sec will complete immediately and move to the call-back queue.
  • Also the Promise with true resolve will complete and move to call-back queue.
  • Then at last first the setTimeout callback function will come into the call stack and then Promise's callback function.
  • So the output will be (I thought) -->
- setTimeout function called
- Promise Resolved function called

But This was not right so first the "Promise Resolved function called" was printed then the "Promise setTimeout function called".

So where did I want wrong, So we were correct till the point where the web API was executing the Promise and setTimeout. But in the call-back queues, there are two types of queues first is Task queue (macrostasks) and then the Job queue(microtasks).

And if the Promise is resolved in the web API. The Promise does not go to the Task queue it goes in the Job queue and the setTimeout or other async API after completion will go to the Task queue.

And this is what makes the difference because the event loop which takes the async APIs from the callback queue and put it into the call stack (after the call stack is emptied) has a priority of dequeueing first the Job queue and then the Task queue.

So that is why the output is.

- Promise Resolved function called
- setTimeout function called

Summary

So the resolved promise is processed faster than an 0-sec setTimeout(). Because of the event loop priorities dequeuing jobs from the job queue which has the promise callback over the task queue which stores the setTimeout() callbacks.

Promise VS setTimeout() in Javascript.