I think this is so basic so people maybe minus votes on this document, but even so this is so confused me about callback function in JavaScript.
function doSomething(callback){
setTimeout(hello,5000);
callback();
}
function hi(){
console.log("hi");
}
function hello(){
console.log("hello");
}
doSomething(hi);
/* result */
// hi
// (after 5 seconds) hello
I want to use callback function as a handle function's execute order, so I decided use callback pattern. In above code, I think after 5 seconds, the callback function should be executed, but why callback ignore before function and was ran first? Could you tell me a some hint.
Thanks.
In your code callback()
was executing after the execution of the line setTimeout()
but the callback of setTimeout
will trigger after 5000ms
, that is the expected behaviour. So if you want callback()
to exeute after hello()
do:
function doSomething(callback){
setTimeout(function(){
hello();
callback();
},5000);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments