【发布时间】:2012-08-20 10:29:43
【问题描述】:
我遇到了正常(非 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...
- 我的更新解决方案
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 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();,不是吗? -
问题是它们都有单独的动画/等,在不同的文件中 - 等等。所以他们最终会发生碰撞......
-
$.when和$.done不一定只适用于 ajax。如果您希望在启动 FunctionTwo 之前在 FunctionOne 中完成各种异步任务,您可以创建Deferred对象,将它们放在一个数组中,在操作完成时对每个对象调用resolve(),然后执行 @987654334 @ -
全局变量是邪恶的,但在这种情况下,可能只需添加一个
isRunning标志即可。 -
您保存了我的应用程序,我永远感激不尽
标签: javascript jquery callback