1

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.

Adam Azad
11.3k5 gold badges31 silver badges74 bronze badges
asked Dec 28, 2015 at 17:40
1
  • Because your timeout doesn't include the callback, it runs on its own Commented Dec 28, 2015 at 17:42

1 Answer 1

4

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);
}
answered Dec 28, 2015 at 17:41
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.