Using jquery how to call a function and call another function from the previous when function execution is completed

StackOverflow https://stackoverflow.com/questions/19558035

Question

I have to perform a task based on jquery. When the page loads, the first jquery function will be called. Once the first function completes successfully, then it should automatically call the next function.

Était-ce utile?

La solution

Here is a working demo JSFIDDLE

JS:

function func_one()
{
    alert('func_one');           
    alert('Now call func_two');   
    func_two();
}

function func_two()
{
    alert('func_two');    
}
//jquery Function block that will be executed on page load
$(document).ready(function(){
    //call the function one
    func_one();
});

Autres conseils

If the function is actually a function then just call it functionA() as per good ol' JavaScript. If it is an event then use Jquery trigger see http://api.jquery.com/trigger/

if it is possible then chaining the functions might also be a good idea.as in FunctionA().FunctionB();

you can 'pass' callback function to other functions. see example:

function one(callback) {
    // do stuff ...
    // do stuff ...
    // do stuff ...

    if (typeof(callback) === 'function') 
        callback();
}

function two() {
}

now, declare document ready and call function one. when it completes, we'll call function two.

$(document).ready(function(){
    one(function(){
        // code after 'one' ended
        two();
    });
});

that's the general idea. hope that helps.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top