MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Callback Functions in JavaScript

In this article we will discuss about the Callback functions in JavaScript.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction:

Let us first understand the execution sequence of javascript code. By default, JavaScript statements are executed sequentially (one after another).But sometime the next line of code can be executed even when the effect of the previous line (code) is not complete. This type of situation causes a lot of error. To prevent this, call back functions are introduced in javascript and it is executed only when the effect of previous code/line is complete.

Callback functions are very commonly used in JavaScript as we know that JavaScript in the browser is single-threaded. In general, a callback is a piece of code which is passed as an argument to some other code. This code calls back or executes the argument as per its convenience. The call back can be either synchronous or asynchronous. Synchronous callbacks are referred as 'Callbacks' while asynchronous callbacks are referred as 'Deferred callbacks'.

Callbacks are used in the situation when an entity which is outside the scope of JavaScript is called and there is a delay in getting the response. In such a scenario, the application can’t keep on waiting for something which may or may not occur. e.g. if we call a function which returns some value and for any reason, the function doesn’t returns the expected value. The code simply keeps on waiting to see if at all any value is returned. Solution to this problem is callbacks. Using call back we can pass a java script function to the server, which gets executed when the result is ready.

Writing a Callback function

To get clarity on callback functions you need to understand regular functions in javascript. Functions in javascript are considered as objects. They can be more specifically described as function objects and they are created with the help of function constructor. The function object contains a string which is actually the javascript code of the function.

In normal programming, functions are called one by one. And once a function is complete the next one is executed. In javascript, it works a bit in a different way. In javascript, we can use javascript callback functions to do asynchronous call rather than waiting for the previous function to complete and then start the next one.

Let us see the following code:

Listing 1: Sample call back function

function myDinner( param1, param2, callbackFunction ) {  
alert( 'Started eating my dinner. \n\n It has: ' + param1 + ', ' + param2);  
    callbackFunction ();  
}
myDinner ( 'Rice', 'Curry', function() {  
    alert( 'Finished eating my dinner.' );  
});

In this example, we have a function called myDinner which accepts three parameters. Here the third parameter is the callback function. When this method is executed it shows an alert message with the passed values displayed. It then executes the callback function. It must be noted here that the actual parameter is just “callbackFunction” (without parentheses), but when we are calling it we call it using the. This parameter is called when it is required. The callback function is declared as the third argument which is passed to the function call. This method has an alert message which indicates that the callback code is executed. Once this code is executed, the following output pops out:

Output of the 1st method

Figure 1: Output of the 1st method

If you click on the 'Ok' button here, you get the following pop up:

Output of the 2nd method

Figure 2: Output of the 2nd method

Callback function is optional:

Callback functions are optional. If there is a method, which accepts a callback function, it won't throw any error if the function is not called. Consider our above example. The same function will result an error if called like this:

Listing 2: Sample function without invoking the callback

function myDinner( param1, param2, callbackFunction ) {  
alert( 'Started eating my dinner.\n\n It has: ' + param1 + ', ' + param2 );  
    callbackFunction ();  
}
myDinner ( 'Rice', 'Curry' );

If we run this code, we get an error "Undefined is not a function" or something similar to that. So to make this callback optional, we modify the above code as under:

Listing 3: Function with optional the callback with a check condition.

function myDinner( param1, param2, callbackFunction ) {  
alert( 'Started eating my dinner.\n\n It has: ' + param1 + ', ' + param2 );  
if ( callbackFunction ) 
    callbackFunction ();  
}
myDinner ( 'Rice', 'Curry' );

Here it should be noted that since there is a check to ensure that the callback function exists, before its execution, the call won't throw an error while execution.

Callback should be function:

While developing the code, it must be ensured that the call back should be a function. In our example, we must ensure that the third parameter is a proper function:

Listing 4: Function with optional the callback with check whether the parameter is actually a function.

function myDinner( param1, param2, callbackFunction ) {  
	alert( 'Started eating my dinner. \n\n It has: ' + param1 + ', ' + param2);  
	if ( callbackFunction && typeof  (  callbackFunction ) ==  "function"  )  {  
    	callbackFunction ();
	} 
}
myDinner ( 'Rice', 'Curry' );

In this piece of code we do a check whether the callback function exists and at the same time we check the type of it. If the callback is of function type, then only it is executed. Now, consider the following piece of code:

The operator typeOf ensures that the parameter passed to it is a function. In this piece of code, we have a third parameter which is not a function but a String. So the callback function is not executed as the typeOf function returns String which is false as per the if statement.

Listing 5: Function with optional the callback when the 3rd parameter is not a function.

function myDinner ( param1, param2, callbackFunction ) {  
	alert( 'Started eating my dinner. \n\n It has: ' + param1 + ', ' + param2);  
	if (callbackFunction && typeof ( callbackFunction )  ==  "function"  )   {  
    	callbackFunction ();
	} 
}
myDinner ( 'Rice', 'Curry' 'Vegetables' );

Timing of Callback function:

It is evident that the callback function will be called at the end when it is placed last as the last line in the code. But this is not guaranteed if the function has some asynchronous call. In this case the callback executes right after the asynchronous call starts and finishes possibly before the asynchronous call ends. Consider the following code:

Note that in the above piece of code, even though the callback function appears after the animation, the call back will be executed much before the animation completes.

Listing 6: Function with optional the callback with an asynchronous call.

function myDinner ( param1, param2, callbackFunction ) {  
	alert( 'Started eating my dinner. \n\n It has: ' + param1 + ', ' + param2 );
$('#dinner).animate({  
opacity: 0  
}, 5000, function() {  
// Animation over.  
});  
	if (callbackFunction && typeof ( callbackFunction )  ==  "function"  )   {  
    	callbackFunction ();
	} 
}
   myDinner ( 'Rice', 'Curry' function() {   
     alert ( 'Finished eating my dinner.' );  
   });   
Usage:

jQuery, which is the most commonly used framework in java script uses callbacks extensively. In our above example (listing 6), the opacity has a delay for 5 minutes. The callback function gets executed before the opacity is executed.

Conclusion:

Before wrapping up, we can conclude that callback functions in javascript make it more flexible. The process of using call back function is also easy to implement and hence it gives a chance to make asynchronous call. To summarize:

  • Callback is a piece of code which is passed as an argument to some other code.
  • Call back should be an appropriate function
  • Callback functions are optional
  • Calbacks can asynchronous or synchronous


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login