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: This is known for sure: EBAD
. C
is unknown when it will be logged.
Explanation: The compiler will not stop on the setTimeout
and the getDataFromDatabase
methodes. So the first line he will log is E
. The callback functions (first argument of setTimeout
) will run after the set timeout on a asynchronous way!
More details:
E
has no setTimeout
B
has a set timeout of 0 millisecondsA
has a set timeout of 1000 millisecondsD
must request a database, after it must D
wait 1000 milliseconds so it comes after A
.C
is unknown because it is unknown when the data of the database is requested. It could be before or after A
.