Gat*_*lan 9 javascript jquery synchronous
我想像jQuery一样同步函数$.ajax({ .., async: false, .. });.
function A() { lalala .. };
function B() { dadada .. };
function C() { .. };
Run Code Online (Sandbox Code Playgroud)
那些都包括fadeIn,Out,slide等等.
但是我刚刚发现这些函数如下所示.
A();
B();
C();
Run Code Online (Sandbox Code Playgroud)
所有效果几乎同时开始.在我的理解中,这是因为函数同步调用但并不意味着函数B()在函数A()完全完成后启动..对吗?
那么,我该如何使这些功能按顺序工作呢?
我找到了一种使用回调函数的方法,但这对我来说还不够..
Jas*_*ans 14
看看使用 jQuery $.Deferred();
这可以让你按顺序运行每个函数,一个接着另一个.例如:
var a = function() {
var defer = $.Deferred();
console.log('a() called');
setTimeout(function() {
defer.resolve(); // When this fires, the code in a().then(/..../); is executed.
}, 5000);
return defer;
};
var b = function() {
var defer = $.Deferred();
console.log('b() called');
setTimeout(function () {
defer.resolve();
}, 5000);
return defer;
};
var c = function() {
var defer = $.Deferred();
console.log('c() called');
setTimeout(function () {
defer.resolve();
}, 5000);
return defer;
};
a().then(b).then(c);
Run Code Online (Sandbox Code Playgroud)
使用defer.resolve();意味着您可以控制函数何时执行下一个函数.