October 22, 2024
Chicago 12, Melborne City, USA
javascript

Understanding JavaScript Execution Order: Synchronous vs Asynchronous with setTimeout and Promises


The code:

console.log("A");
setTimeout(() => {
  console.log("B");
  Promise.resolve("C").then(() => console.log("D"));
});
setTimeout(() => console.log("E"), 0);
console.log("F");

And the task is to determine the order of letters.

The first two are A and F, since they are sync.
Then we have two async setTimeout functions, and they are queued. Since it is a queue, the first one is:

setTimeout(() => {
  console.log("B");
  Promise.resolve("C").then(() => console.log("D"));
});

Here the B is sync, so it gets executed, and then D.
And the last is E.

So the final order

A
F
B
D
E

Am I right? Is my thought proccess right? Do you have any tips/ algorythm how to determine the order of execution in problems/ questions like this?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video