7

I would like to create a custom callback function for a custom function and pass callback as a parameter.

function customFunction(a, b, callback) {
  // Some code
}

customFunction("val1", "val2", function(){
  //Code to execute after callback
});

2 Answers 2

8

You're almost there...

function customFunction(a, b, callback) {
    // Some code
    if (typeof callback === 'function') { 
        callback(); 
    }
}

customFunction("val1", "val2", function(){
  //Code to execute after callback
});
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting "Uncaught TypeError: callback is not a function"
I'd add if (typeof callback === 'function') { callback(); } in case you have no 3rd parameter.
Thanks, "if (typeof callback === 'function') { callback(); }" solved the issue :)
I've added that in to the solution
1

The solution of Coulson is good. To show it more clearly we can add the timeout function as follow:

function customFunction(a, b, callback) {
     setTimeout(function(){
      console.log("original function");
      callback();
     },1000);


}

$(document).ready(function() {
    $('#test').click(function() {
        customFunction("val1", "val2",function(){
            console.log("callback function");
       });
    });
});

Following is the link for check - https://jsfiddle.net/y0ch9exw/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.