Skip to content Skip to sidebar Skip to footer

Callback Gets Called Before Rest Of The Function Executed

I recreated this example (from link given below) to understand callbacks. The problem is that the callback gets executed before the parent function 'first()' finishes. setTimeout w

Solution 1:

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):

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

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

first(second);

Solution 2:

Here you are calling "callback" synchronously which means first function will wait for second(callback) function to be completed and then proceed with it's execution. To understand it better I have put console log at other places as well. Pls try below and see if you now have better understanding for the same

functionsecond() {
	console.log('second method started')
        setTimeout(() =>console.log("second function executed"), 1000)
	console.log('second method finished')
}

functionfirst(callback){
	console.log('first method started')
        setTimeout(() =>console.log("first function executed"), 1000 );
        callback();
	console.log('first method finished')
}

first(second);

Post a Comment for "Callback Gets Called Before Rest Of The Function Executed"