Code example

suggest change

Question: What is the output of code below and why?

setTimeout(function() {
    console.log("A");
}, 1000);

setTimeout(function() {
    console.log("B");
}, 0);

getDataFromDatabase(function(err, data) {
    console.log("C");
    setTimeout(function() {
        console.log("D");
    }, 1000);
});

console.log("E");

Output: E, B, A, and D are logged in that order. C is logged when the database callback runs, which is before D and may be before or after A.

Explanation: The runtime does not wait on setTimeout or getDataFromDatabase. The first line logged is E. Each setTimeout callback runs later, on a later turn of the event loop.

More details:

  1. E has no setTimeout.
  2. B is scheduled with a timeout of 0 milliseconds, so it runs before the 1000-millisecond timer.
  3. A is scheduled with a timeout of 1000 milliseconds.
  4. D is scheduled only inside the database callback, and then waits another 1000 milliseconds, so it is logged after A.
  5. C depends on when the database responds. It can be logged before or after A, but always before D.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents