Jquery在用户定义的函数之间等待

时间:2013-06-13 15:34:16

标签: jquery function callback wait

我有两个功能,tick和tock。它们导致4个数字旋转一个方向然后旋转另一个方向。每个号码都可以以不同的速度缓和。

我可以调用这两个函数,但我不能让第二个(tock)等到所有数字都在第一个(tick)中完成移动。

我已经查看过使用回调的其他类似问题,但我似乎无法用我的示例实现这一点。我要么在完成第一个函数之前完成第二个函数,要么就像下面的代码一样,只使用第一个函数。

由于

$(document).ready(function(){
var complete = 0;

tick('', function(){tock();});

function tick(a){

    $('#col1 img')
        .delay('1000')
        .animate({bottom:'-=80px'},5000,'easeInOutSine');
        complete++;

    $('#col2 img')
        .delay('1000')
        .animate({bottom:'+=720px'},1000,'easeInOutSine');
        complete++;


    $('#col3 img')
        .delay('1000')
        .animate({bottom:'+=560px'},500,'easeInOutSine');
        complete++;


    $('#col4 img')
        .delay('1000')
        .animate({bottom:'-=240px'},2000,'easeInOutSine');
        complete++;

}

function tock(){
    $('#col1 img')
        .delay('1000')
        .animate({bottom:'+=80px'},2000,'easeInOutSine');

    $('#col2 img')
        .delay('1000')
        .animate({bottom:'-=720px'},2000,'easeInOutSine');

    $('#col3 img')
        .delay('1000')
        .animate({bottom:'-=560px'},2000,'easeInOutSine');

    $('#col4 img')
        .delay('1000')
        .animate({bottom:'+=240px'},2000,'easeInOutSine');
}
});

1 个答案:

答案 0 :(得分:4)

您必须等到所有动画完成后再调用另一个动画。所有jQuery对象都实现了promise interface [docs],并且在任何动画完成后它们都会被解析。与$.when [docs]一起,您可以轻松实现您想要的目标:

function tick(callback){

    var p1 = $('#col1 img')
        .delay('1000')
        .animate({bottom:'-=80px'},5000,'easeInOutSine')
        .promise();

    var p2 = $('#col2 img')
        .delay('1000')
        .animate({bottom:'+=720px'},1000,'easeInOutSine')
        .promise();


    var p3 = $('#col3 img')
        .delay('1000')
        .animate({bottom:'+=560px'},500,'easeInOutSine')
        .promise();


    var p4 = $('#col4 img')
        .delay('1000')
        .animate({bottom:'-=240px'},2000,'easeInOutSine')
        .promise();

    // $.when returns a new promise which is resolved once each passed promise 
    // is successfully resolved
    $.when(p1, p2, p3, p4).done(callback);
}

function tock(){
    // same as the original code
}

tick(tock);

有关承诺/延期的更多信息:http://api.jquery.com/category/deferred-object/


由于如此多的代码重复让我感到焦虑,这里是tick函数的重构版本:

function tick(callback) {
    var data = [
        {props: {bottom: '-=80px'}, duration: 5000},
        {props: {bottom: '+=720px'}, duration: 1000},
        {props: {bottom: '+=560px'}, duration: 500},
        {props: {bottom: '-=240px'}, duration: 2000}
    ];
    var promises = [];

    // assuming the elements are in the correct document order
    $('#col1, #col2, #col3, #col4').find('img').each(function(i) {
        var d = data[i];
        promises.push(
            $(this).delay(1000).animate(d.props, d.duration, 'easeInOutSine').promise()
        );
    });

    $.when.apply($, promises).done(callback);
}