I am confused about the example in http://dreamerslab.com/blog/en/javascript-callbacks/
function do_a(){
// simulate a time consuming function
setTimeout( function(){
console.log( '`do_a`: this takes longer than `do_b`' );
}, 1000 );
}
function do_b(){
console.log( '`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`' );
}
do_a();
do_b();
results
`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`
`do_a`: this takes longer than `do_b`
and the author’s explanation is “However javascript is an event driven language. If do_a takes longer than do_b, the result of do_b comes out first than do_a;”. I am still not quite clear, please explain in details, or please point me to some specific material, thank you,
setTimeout says to execute its function after 1 second. Each function returns immediately, while setTimeout executes after that time.
In actuality, do_a() and do_b() are executing in order. But the results of setTimeout are independent of do_a or do_b.
Further, that is a poor example of callback function execution since setTimeout has nothing to do with a callback. A better example is as follows: