callback gets called before rest of the function executed

It appears that you misunderstand how setTimeout() works. This tool called Loupe by Philip Roberts may help you understand. I’ve taken your code placed it into the tool which will allow you to visualise what is actually happening – link to Loupe

When you use setTimeout, that function provided as the first parameter is delayed for the number of milliseconds provided in the second parameter (in your example, this is 1000). The rest of your code will continue to execute in order until this timeout has lapsed.

If you want your callback function to execute after the given timeout: you can actually just write it such like:

setTimeout(callback, 1000) <- Since callback is already a function, you don’t need to wrap it in another function unless you wish to do other operations before calling the callback.

Update 1 (2018-10-26):

function second() {
    console.log("second/callback function")

function first(callback){
    console.log("first function")
    setTimeout(callback, 1000);


Leave a Comment