Callback confusion kindly help

Callback confusion kindly help
0

#1

Hi,

I was just trying use callback function and felt i understood them well , ie they are functions that are called by other function when the “other” function is done doing what it it suppose to do …

But when i run this code -


function doCallBack(callback) {
    setTimeout(function(){
       console.log("Doing work");
    },3000);
   
    callback();
}

doCallBack(function () {
   console.log("Done waiting for 3 seconds"); 
});

I find despite the setTimeout for 3 seconds the output is Done waiting 3 seconds and then Doing work …

Kindly guide why is the callback getting called first rather then waiting for 3 seconds … Thanks


#2

What happens roughly when you call doCallBack is

  1. The setTimeout function is called. It sets the function that you pass it to run 3 seconds after there’s nothing else in your code to run.
  2. The callback function is called. The console prints 'Done waiting for 3 seconds'.
  3. There’s nothing else to be done in your code. At this point, the timeout that you set kicks in after 3 seconds.
  4. 3 seconds later, the console prints 'Doing work'.

setTimeout doesn’t pause execution of code. Rather it schedules code that you pass it to run some time later after your code runs. This scheduling doesn’t take too much time, and immediately after that the code after it runs.


#3

Thank you so much i tried this below and seems to work as expected -


function doCallBack(callback) {
    var ms = 3000 + new Date().getTime();
    while(ms > new Date().getTime()){
        
    }
    callback();
}

function callback() {
    console.log("Done waiting for 3 seconds"); 
}