70

それぞれに多くのアニメーションが含まれる通常の ( 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();

});
4

9 に答える 9

110

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);

複数の deferred を一緒にパックすることもできます:

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();
    });
  });
};

http://jsfiddle.net/p22dK/

于 2012-08-27T10:20:46.950 に答える
3

ヨッシーの答えに加えて、アニメーション用の別の非常に単純な (コールバック タイプ) ソリューションを見つけました。

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);
};

基本的な使い方:

functionOne(); // one with animations

animationsTest(functionTwo);

これが何人かの人々を助けることを願っています!

于 2013-07-24T02:47:14.813 に答える
2

この回答ではpromisesECMAScript 6標準の JavaScript 機能である を使用しています。ターゲット プラットフォームが をサポートしていない場合はpromises、PromiseJs でポリフィルします。

アニメーション呼び出しでDeferred使用して、アニメーション用に jQuery が作成するオブジェクトを取得できます。.promise()これらDeferredsES6Promisesにラップすると、タイマーを使用するよりもはるかにクリーンなコードになります。

直接使用することもできますがDeferreds、Promises/A+ 仕様に従っていないため、一般的にはお勧めできません。

結果のコードは次のようになります。

var p1 = Promise.resolve($('#Content').animate({ opacity: 0.5 }, { duration: 500, queue: false }).promise());
var p2 = Promise.resolve($('#Content').animate({ marginLeft: "-100px" }, { duration: 2000, queue: false }).promise());
Promise.all([p1, p2]).then(function () {
    return $('#Content').animate({ width: 0 }, { duration: 500, queue: false }).promise();
});

Promise.all()の関数が promiseを返すことに注意してください。ここで魔法が起こります。then呼び出しで promise が返された場合、次のthen呼び出しは実行前にその promise が解決されるのを待ちます。

jQuery は、要素ごとにアニメーション キューを使用します。したがって、同じ要素のアニメーションは同期的に実行されます。この場合、Promise をまったく使用する必要はありません。

プロミスでどのように機能するかを示すために、jQuery アニメーション キューを無効にしました。

Promise.all()Promisepromise の配列を取り、配列内のすべての promise が終了した後に終了する new を作成します。

Promise.race()も promise の配列を取りますが、最初のものが終了するとすぐにPromise終了します。

于 2015-09-23T06:52:44.963 に答える
1

ECMAScript 6 アップデート

これは Promises と呼ばれる JavaScript の新機能を使用します。

functionOne().then(functionTwo);

于 2016-03-30T19:45:54.977 に答える
1

これはあなたが意味するものですか: http://jsfiddle.net/LF75a/

1 つの関数が次の関数を起動するようになります。つまり、別の関数呼び出しを追加functionONeし、その下に your を追加します。

私が何かを逃した場合はお知らせください。それが原因に適合することを願っています:)

またはこれ:前の関数が完了した後に関数を呼び出す

コード:

function hulk()
{
  // do some stuff...
}
function simpsons()
{
  // do some stuff...
  hulk();
}
function thor()
{
  // do some stuff...
  simpsons();
}
于 2012-08-24T20:59:07.223 に答える
0

これは、n-calls (再帰関数) のソリューションです。 https://jsfiddle.net/mathew11/5f3mu0f4/7/

function myFunction(array){
var r = $.Deferred();

if(array.length == 0){
    r.resolve();
    return r;
}

var element = array.shift();
// async task 
timer = setTimeout(function(){
    $("a").text($("a").text()+ " " + element);
    var resolving = function(){
        r.resolve();
    }

    myFunction(array).done(resolving);

 }, 500);

return r;
}

//Starting the function
var myArray = ["Hi", "that's", "just", "a", "test"];
var alerting = function (){window.alert("finished!")};
myFunction(myArray).done(alerting);
于 2015-08-18T12:28:14.667 に答える
0

コールバック関数を介して行うことができます。

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});

function function1(param, callback) { ...何かを行う callback(); }

于 2015-03-04T06:21:02.257 に答える