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.

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.