我在处理一些包含大量动画的普通(非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);
有没有办法在js/jQuery中实现以下功能:
// Pseudo-code
-do FunctionOne()
-when finished :: run -> FunctionTwo()
我知道$.when()
和$.done()
用于AJAX,但那些只是针对AJAX的。
- 我的更新解决方案
jQuery有一个暴露的变量(在jQuery文档中没有列出原因不明),叫做$.timers,其中包含当前正在进行的动画数组。
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 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();
});
FunctionOne
没有超时或其他问题,你可以直接调用FunctionOne(); FunctionTwo();
,对吗? - Waleed Khan$.when
和$.done
不一定只适用于ajax。如果您在FunctionOne中有各种异步任务需要完成,然后再启动FunctionTwo,您可以创建“Deferred”对象并将它们放入数组中,在每个任务完成时调用resolve()
,最后使用$.when.apply($, array).then(function(){...});
来处理。 - MrOBrianisRunning
标志可能是值得的。 - ajax333221