3

I'd like to create a callback on a simple function.

I have this function which is called on button click:

function main(){ };

So I'd like main(), when its done to call this:

 function test(){ }

3 Answers 3

4
function main(callback) {
    // ... do your thing
    callback();
}

main(function(){
    alert('this is the callback speaking');
});
Sign up to request clarification or add additional context in comments.

1 Comment

@jQuerybeast: You pass your test function as the callback parameter of main. Updated my answer with more details
3

if the main() function not use ajax,you can use:

function main(callback) {
    // ... do your thing
    callback();
}

function test(){}

eg:
<input type="button" onclick="main(test);"/>

if the main() function use ajax,you can call test() in complete function like this:

function main(callback){
    $.ajax({
        ...
        complete: function(XMLHttpRequest, textStatus){
            callback(); 
        },
        ...
    });
}

function test(){
    ...
}
eg:
<input type="button" onclick="main(test);" value="test"/>

2 Comments

Hi and thanks. I am not using ajax. On your first example, the API doesn't allow me to call main(test). Example: API.loadAndWait('snippet', '5', main); so if I replace the main with main(test) it doesnt compile
In that case you would have to use something like API.loadAndWait('snippet', '5', function() {main(test);});
1

As i understood its simple,Sorry if i am not in the point.

function main() {
// ... do your thing
test();
}


function test() {
// ... do your thing in test

}

3 Comments

That's what I thought, but test is executed with the main
So whats the deference?If you want to execute test after the main this is it.Or if you want to call test few minutes after main use setTimeout("test()",3000); .Then it will be called after 3000 milliseconds.
Not when you only execute test() after(!) you did whatever you have to do in main(). We don't know your code so we cannot guess where in your code you'll have to place the call to test(). Show us more code an we can help you

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.