我在正常( 非ajax )函数中遇到了问题,每个函数中都包含许多 动画 。目前,我只是具有一个setTimeoutbetween函数,但这并不是完美的,因为没有浏览器/计算机是相同的。
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的…
$.when()
$.done()
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(); });
您可以使用jQuery的 $.Deferred
$.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);
您还可以将多个延期打包在一起:
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(); }); }); };