Mar*_*.io 67 javascript jquery callback
我遇到了普通(非ajax)函数的问题,这些函数在每个函数中都涉及很多动画.目前我只有一个setTimeout
功能之间,但这并不完美,因为没有浏览器/计算机是相同的.
附加说明:它们都有单独的动画/等碰撞.
我不能简单地把一个放在另一个的回调函数中
// multiple dom animations / etc
FunctionOne();
// What I -was- doing to wait till running the next function filled
// with animations, etc
setTimeout(function () {
FunctionTwo(); // other dom animations (some triggering on previous ones)
}, 1000);
Run Code Online (Sandbox Code Playgroud)
无论如何在js/jQuery中有:
// Pseudo-code
-do FunctionOne()
-when finished :: run -> FunctionTwo()
Run Code Online (Sandbox Code Playgroud)
我知道$.when()
&$.done()
,但那些是针对AJAX的......
jQuery有一个名为$ .timers的暴露变量(由于某种原因未在jQuery文档中列出),它包含当前正在进行的动画数组.
function animationsTest (callback) {
// Test if ANY/ALL page animations are currently active
var testAnimationInterval = setInterval(function () {
if (! $.timers.length) { // any page animations finished
clearInterval(testAnimationInterval);
callback();
}
}, 25);
};
Run Code Online (Sandbox Code Playgroud)
基本用途:
// run some function with animations etc
functionWithAnimations();
animationsTest(function () { // <-- this will run once all the above animations are finished
// your callback (things to do after all animations are done)
runNextAnimations();
});
Run Code Online (Sandbox Code Playgroud)
Yos*_*shi 109
你可以使用jQuery $.Deferred
var FunctionOne = function () {
// create a deferred object
var r = $.Deferred();
// do whatever you want (e.g. ajax/animations other asyc tasks)
setTimeout(function () {
// and call `resolve` on the deferred object, once you're done
r.resolve();
}, 2500);
// return the deferred object
return r;
};
// define FunctionTwo as needed
var FunctionTwo = function () {
console.log('FunctionTwo');
};
// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);
Run Code Online (Sandbox Code Playgroud)
你也可以将多个延期包装在一起:
var FunctionOne = function () {
var
a = $.Deferred(),
b = $.Deferred();
// some fake asyc task
setTimeout(function () {
console.log('a done');
a.resolve();
}, Math.random() * 4000);
// some other fake asyc task
setTimeout(function () {
console.log('b done');
b.resolve();
}, Math.random() * 4000);
return $.Deferred(function (def) {
$.when(a, b).done(function () {
def.resolve();
});
});
};
Run Code Online (Sandbox Code Playgroud)
que*_*ful 13
将以下内容添加到第一个函数的末尾
return $.Deferred().resolve();
Run Code Online (Sandbox Code Playgroud)
称这两个函数都是这样的
functionOne().done(functionTwo);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
192983 次 |
最近记录: |