Javascript callbacks

Javascript, the ‘Mickey mouse’ language is already started to gain more acceptance in all area of web development from the client side and even to the server side. This era of client side architecture also increased the popularity of javascript. So I am just thinking of writing a note on most interesting features of javascript.

Callbacks in javascript

Simply saying, a callback is just ‘functions’ as ‘arguments’. Well, a search on web can say….

a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time.
-wikipedia

The special part of callback is, even people used callback doesn’t know how to use it. interesting isn’t it!!!. Why I said that I have seen people worked with jQuery to add event listeners argue they dont know callback. We will look into jQuery and callback later, but now we can take a look into ‘what is’ and ‘why’ callbacks.

Why do we need Callbacks?

Because javascript executions are asynchronous. What does that mean? simply saying they executes line by line and ‘it will not wait for one function to complete its execution to execute the next function’. Lets take a look with an example. Suppose we need to write a program for following scenario.

Scenario

  • I need two functions; first function prints the word ‘hello’ and second function prints ‘world’.
  • I need a button to start the execution and the first word(‘hello’) should be printed after 2 seconds I click the button. Second word(‘world’) prints just after the first word.

So lets start writing the code, I use setTimeout for 2 seconds of delay to start printing the first word.

…and create the button to call ‘show()’ function on click.

So; what we did is, we created a button, which calls the function 'show()' which internally calls function 'showFirstElement()'. The function 'showFirstElement()' waits for 2 seconds and prints ‘hello’; Then the second function named 'showSecondElement()' is called which will print the word ‘world’.

Ok.. all is done!!. lets try run this code. You can see the result in JSFiddle..

oops!! As you see the word ‘world’ is printed first and the word ‘hello’ prints next. This behavior is a result of asynchronous execution.

What happened here is the control didn’t waited for completing the function 'showFirstElement()'. It simply executed first function –'showFirstElement()' (ie. it waited 2 seconds for printing) and then executed the second function 'showSecondElement()'. The 2 second delay happened only after completing the second function- 'showSecondElement()'. After this 2 second delay it completed first function- 'showFirstElement()' by printing ‘hello’.

So how can we fix the problem?

Writing callbacks

Yes… writing call back is the best solution for this. Lets try out one.
We can call the 'showSecondElement' from within the 'showFirstElement'. But the 'showFirstElement' doesn’t need not to know anything about what to do next(ie. what to call, whether it is 'showSecondElement' or something else. Here this is decided by the function 'show').
But one thing the 'showFirstElement' can do is, it can call any ‘callback’ function passed to it. And since the 'show' knows what to do after 'showFirstElement', it can pass 'showSecondElement' as a callback to 'showFirstElement'. Look at the code follows.

Try the result in JSFiddle.
Now you can see that the code is working as expected.

Generally, we need to ensure that the passed argument is a function before calling, as follows.

Try in JSFiddle
So… thats it. This is how we write callbacks and we use it.

callbacks in jQuery

Ok, well take a look into jQuery event listeners.

Example-1

Those of who familiar with jQuery has already know it. For others this is a simple function which gives a javascript alert when clicking on an element with id 'myButton'.

Try in JSFiddle.

So this is a typical example of callback. If you look more detail into this piece of code, there are two parts. Firstly we attached a 'click' event to element with id 'myButton'; then we told browser what to do when a user clicks on the 'myButton' element.

To understand it clearly, we can split the above code into two parts.

The above example gives the same result as before. Try in JSFiddle.

If you look into the code, we defined a function named 'calbak' and then we used that function in another function 'click' as its argument. So we passed the 'calbak' function into 'click' function. In the example-1 we just used an anonymous function to define what to do when user clicks the button.

So that is how we use callbacks in jQuery.

Leave a Comment

Your email address will not be published. Required fields are marked *