9

I was browsing the html5boilerplate github and I went to see some of the interview questions and I came across this one and I don't understand why it outputs in the order it does. I assumed it would be one four two three not the output it does. Can someone explain why? sorry if it's too simplistic.

Question: What does the following code print?

console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
Promise.resolve().then(function() {
  console.log('three');
})
console.log('four');

The output was in this order "one" "four" "three" and finally "two"

Code Snippet

console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
Promise.resolve().then(function() {
  console.log('three');
})
console.log('four');

2
  • Imho, the first two should be clear. Afterwards, promises are put into a microtask queue, which gets completed before the main event queue, that does e.g. setTimeout tasks.
    – ASDFGerte
    Aug 7, 2018 at 14:09
  • 2
    @gforce301 considering my question covers "a specific programming problem" then I don't know how it's not appropriate for SO
    – Nen
    Aug 7, 2018 at 14:23

2 Answers 2

32

I think output one and four are pretty clear. setTimeout is a part of Main Task queue while Promise is of Micro task queue that's why "three" and finally "two" is printed.

Step by Step execution is as below:

  1. When script is executed, console.log(“one”) is executed first.

  2. When setTimeout(…) is encountered, runtime initiates a timer, and after 0ms. Callback function() {} of setTimeout(…) is queued in Task queue.

  3. When promise object is encountered, its callback i.e function() {} is queued in Micro task queue.

  4. Finally, it executes last console.log(“four”) .

According to standard specification

  1. Once a call stack is emptied, it will check Micro task queue and finds callback function() {} of promise.Call stack will execute it (logs three).

  2. Once again, call stack is emptied after processing callbacks in Micro task queue. Finally, event loop picks up a new task from the Task queue i.e callback function() {} of setTimeout(…) ( logs two) execute it.


Visual Image

Visual Image

console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
Promise.resolve().then(function() {
  console.log('three');
})
console.log('four');

1
  • 2
    dude your answer went above and beyond to explain this and honestly I really appreciate it
    – Nen
    Aug 7, 2018 at 15:37
3

This is due to the JS call stack; both setTimeout and Promise.resolve().then are asynchronous calls.

setTimeout(function(){...}, 0) simply queues the code to run once the current call stack is finished executing, exactly the same as Promise.resolve().then() (albeit to a subqueue). The subqueue finishes executing hence why three appears before two, and then the main queue is finished, so setTimeout can now be called.

8
  • This is simply wrong, and also would not explain the output. Promise.resolve().then() is exactly not in the same queue as setTimeout.
    – ASDFGerte
    Aug 7, 2018 at 14:11
  • 1. What's specifically incorrect? 2. I'm not suggesting they're both the same in terms of functionality. I'm saying that they're both async calls that execute once the current call stack is finished. Check the spec...
    – BenM
    Aug 7, 2018 at 14:12
  • @ASDFGerte A Promise in the pending status. The handler function (onFulfilled or onRejected) then gets called asynchronously (as soon as the stack is empty)
    – BenM
    Aug 7, 2018 at 14:13
  • Switching the order of the setTimeout and .then in the code will not change the output order. They are different queues, and not "exactly the same".
    – ASDFGerte
    Aug 7, 2018 at 14:14
  • 1
    Promise.resolve queues what's called a microtask which is called just after the end of the execution of the current execution block. setTimeout on the other hand schedules a task which has less priority than microtasks. Both are async. and are queued for later execution, but microtasks take priority. Aug 7, 2018 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.