简体   繁体   中英

jQuery/Javascript Delay Execution of a Function Until Several Functions Have Completed

I have a tricky situation. I need to delay execution of a function until several functions have completed. While the following would work in a normal situation:

    $.when(foo1(), foo2(), foo3()).then(function(){
        //foo4();
    });

My situation is a little different. I don't want the functions passed to $.when() to execute immediately. foo1-3 will be executed at some point in the near future, by other methods. In other words, I want to execute foo1-3 manually, at a time of my choosing. Only after foo1-3 have executed (in no specific order) will foo4 run.

My intuition told me to dig into $.Deferred() , but I haven't quite found what I need. Any ideas?

Have the fooX functions resolve deferreds which are passed to $.when .

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

function foo1() {
    // do normal work, then
    d1.resolve();
}

// same for other 2 functions

$.when(d1, d2, d3).then(foo4);

http://jsfiddle.net/mattball/nVFnv/

Make a scoreboard variable that counts up as each function completes, then call foo4 after each function. foo4 should exit if the score has not counted up to the correct value.

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