Anjishnu
Anjishnu

Reputation: 93

How to identify the behaviour of a callback function?

The following are two examples -

function someFunc(a){
    return a**2;
}

function calling(value,f){
    return f(value)+2;
}

calling(3,someFunc);

and

const message = function() {  
    console.log("This message is shown after 3 seconds");
}
 
setTimeout(message, 3000);

In the first example, someFunc is executed first for the calling function to return a value; while in the second example, the program execution is paused for 3 seconds before the message function is called.

Is the function someFunc in the first example a callback function? Also, how is the message function in the next example not executed prior to the timeout? Any answer would greatly help.

Upvotes: 0

Views: 27

Answers (1)

Quentin
Quentin

Reputation: 943157

In the first example, someFunc is executed first for the calling function to return a value

No, it isn't.

calling is executed and someFunc is passed to it as an argument.

calling then calls someFunc (which was copied into f).

Then calling returns a value.

while in the second example, the program execution is paused for 3 seconds before the message function is called.

No, it isn't.

setTimeout puts message on a queue with a note that it shouldn't be executed for at least three seconds.

The program then continues. It doesn't do anything because there is nothing for it to do, but it isn't paused.

Is the function someFunc in the first example a callback function?

Yes

Also, how is the message function in the next example not executed prior to the timeout?

Because mentioning the name of a variable holding a function doesn't call the function.

You need to do something to call it, such as using ().

Upvotes: 2

Related Questions