Code example
suggest changeQuestion: 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:
Ehas nosetTimeout.Bis scheduled with a timeout of 0 milliseconds, so it runs before the 1000-millisecond timer.Ais scheduled with a timeout of 1000 milliseconds.Dis scheduled only inside the database callback, and then waits another 1000 milliseconds, so it is logged afterA.Cdepends on when the database responds. It can be logged before or afterA, but always beforeD.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents