callback function in custom function

javascript, jquery

Solution

You can create a function pointer with something like:

var yourCallback = function() {
    alert('2');
}

You can think of it as an object containing the function itself (not its return value). Since it is an object, you can pass it around to other functions.

Then pass that to the function you are calling as an argument (do not invoke it with `()`, as that would pass its return value):

function1(params, yourCallback);

Finally, in function1, invoke your callback when you need it:

function function1(args, callback) {
    //Some code
    if (callback) {
        callback();
    }
}

Problem

is there a way to call a custom function after another completes. Lots of jquery includes a way to do a call back, like when an animation completes you can just give it another function as a last parameter. But is there anyway to string together `function1(params, function1(){alert('2');})` or something? I honestly have no idea how it would look. Thank you

Original source