callback function meaning

JavaScript’s “callback” is function object that can be passed to some other function (like a function pointer or a delegate function), and then called when the function completes, or when there is a need to do so. For example, you can have one main function to which you can pass a function that it will call…

Main function can look like this:

function mainFunc(callBack)
{
    alert("After you click ok, I'll call your callBack");

    //Now lets call the CallBack function
    callBack();
}

You will call it like this:

mainFunc(function(){alert("LALALALALALA ITS CALLBACK!");}

Or:

function thisIsCallback()
{
    alert("LALALALALALA ITS CALLBACK!");
}

mainFunc(thisIsCallback);

This is extensively used in javascript libraries. For example jQuery’s animation() function can be passed a function like this to be called when the animation ends.

Passing callback function to some other function doesn’t guarantee that it will be called. Executing a callback call (calBack()) totally depends on that function’s implementation.

Even the name “call-back” is self-explanatory… =)

Leave a Comment