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: 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:
Ehas nosetTimeoutBhas a set timeout of 0 millisecondsAhas a set timeout of 1000 millisecondsDmust request a database, after it mustDwait 1000 milliseconds so it comes afterA.Cis unknown because it is unknown when the data of the database is requested. It could be before or afterA.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents