简体   繁体   中英

How do I execute a function after completing first function?

I have a JavaScript function func1() :

function func1() {
    do some stuff;
}

and another JavaScript function func2() .

function func2() {
    do some other stuff;
}

After completing func1() , how can I call func2() ?

I know how to define callback handler for events like 'onclick', but I don't know how to call func2() after func1() has been executed completely.

Either:

function func1() { 
    // Everything else
    func2();
}

or

func1();
func2();

or, if func1 does something asynchronous, then you need some way to tell when it is finished. That will probably involve setting up an event handler, but the specifics depend very much on what the function actually does.

An alternative method to what others have suggested (calling a global function at the end of the first function) is:

function f1(callback) {
    //do some stuff
    callback();
}

function f2() {
    //do some other stuff
}

f1(f2);

javascript is not multithreaded so I don't see what's the complication here. You should be able to do this:

function func1() {
    do some stuff;
    func2();
}
function func2() {
    do some other stuff;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM