javascrip callback

How Callback Functions Work?

Because functions are first-class objects in JavaScript, we can treat functions like objects, so we can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. We aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.

And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime. This allows us to execute the callback functions at any point in the containing function.

It is important to note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function’s body. So, even though the first jQuery example looked like this:

//The anonymous function is not being executed there in the parameter. 
//The item is a callback function
$("#btn_1").click(function() {
  alert("Btn 1 Clicked");
});

The anonymous function will be called later inside the function body. Even without a name, it can still be accessed later via the arguments object by the containing function.

 

Defining Functions with Callback Arguments

So far we have been looking at the “client” side where the call originates and the callback function is defined. Now let’s look at the other side, where the original call gets processed, and from where the callback is invoked.

Here is a simple maths function that generates a random number between two values, min and max, and passes the result to a callback function:

1
2
3
4
5
function randomGenerator(min, max, callback)
{
   var myNumber = Math.floor(Math.random() * (max - min + 1)) + min;
   setTimeout(function() { callback(myNumber); }, 500);
}

This maths function accepts three arguments, the third of which is the callback function to which the results should be sent. The function first does the required calculation (using the values of the first two arguments), then we make it wait 500 milliseconds (usingsetTimeout) before invoking the callback function passing the result.

(We are using setTimeout here merely to simulate what might happen with a complex asynchronous computation of a random number — imagine how slow your app could become if this function is called multiple times and you had to wait each time for the result via a standard return from the called function.)

On the client side, we can now make use of our random number generation function like this:

1
2
3
4
randomGenerator (5, 15, function(num)
{
   console.log("Your number is " + num);
});

Five hundred or so milliseconds later our random number will be passed to our callback function and written to the console.

 

Closures

A callback function can be used as a closure. A closure is a function that remembers references to variables outside of it’s local scope. By this we mean variables that are neither parameters of the function, nor local variables defined inside the function with var keyword, but variables defined outside of the function, for example global variables or local variables defined in the containing function. Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Global variable.
var name = "Chris";
function lottery()
{
   // Local variables.
   var win = ", you win!";
   var lose = "Better luck next time ";
   // The function in the third parameter is a closure
   // that refers to the variables name, win, lose.
   randomGenerator (0, 100, function(num)
   {
      if (num > 50)
      {
         alert(name + win);
      }
      else
      {
         alert(name + lose);
      }
   });
}

In the above example, the function randomGenerator will return more or less instantly, and then the function lottery will return instantly. Then, 500 milliseconds later, the callback will be invoked. This means that, even though the function lottery is no longer running, the local variables win and lose are available to the callback, since it is a closure function. All functions in JavaScript have the capability to be closures that remember references to external variables.

 

FROM HERE AND HERE

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s