[英]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. 我不希望传递给
$.when()
的函数立即执行。 foo1-3
will be executed at some point in the near future, by other methods. foo1-3
将在不久的将来通过其他方法执行。 In other words, I want to execute foo1-3
manually, at a time of my choosing. 换句话说,我想在选择的时候手动执行
foo1-3
。 Only after foo1-3
have executed (in no specific order) will foo4
run. 只有在执行
foo1-3
(没有特定顺序)之后, foo4
才会运行。
My intuition told me to dig into $.Deferred()
, but I haven't quite found what I need. 我的直觉告诉我要深入研究
$.Deferred()
,但是我还没有找到我需要的东西。 Any ideas? 有任何想法吗?
Have the fooX
functions resolve deferreds which are passed to $.when
. 让
fooX
函数解析传递给$.when
fooX
延迟。
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/ http://jsfiddle.net/mattball/nVFnv/
Make a scoreboard variable that counts up as each function completes, then call foo4 after each function. 制作一个记分板变量,该变量在每个函数完成时计数,然后在每个函数之后调用foo4。 foo4 should exit if the score has not counted up to the correct value.
如果分数未达到正确值,则foo4应该退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.