在调用函数之前等待动画完成

时间:2013-03-30 12:14:20

标签: javascript jquery

JS:

$.fn.blink = function(times, duration) {
    times = times || 2;

    while (times--) {
        this.fadeTo(duration, 0).fadeTo(duration, 1);
    }      
};

这会使文字闪烁。最后眨眼我想执行一个函数,所以我改变了它:

$.fn.blink = function(times, duration, callback) {
    times = times || 2;

    while (times--) {
        this.fadeTo(duration, 0).fadeTo(duration, 1);
    }

    if (typeof callback == 'function') { // make sure the callback is a function
        callback.call(this); // brings the scope to the callback
    }
};

回调的执行不在正确的位置。当眨眼开始时似乎被解雇了。有关如何在最后一次闪烁时调用该功能的想法吗?

FIDDLE

2 个答案:

答案 0 :(得分:1)

jQuery动画有一个complete回调参数,因为这些方法是异步的

尝试:

while (times--) {
        this.fadeTo(duration, 0).fadeTo(duration, 1, function(){
            /*last animation is complete*/
           if (typeof callback == 'function') { // make sure the callback is a function
                callback.call(this); // brings the scope to the callback
            } 

        });
    }

API参考:http://api.jquery.com/fadeTo/

答案 1 :(得分:1)

我给你写了一个小提琴。您的代码的问题是,循环通过闪烁的东西迭代到快速,并且立即调用完整的函数。

$(document).ready(function () {
    $('.blink').blink(5, 500, shout);
});

function shout() {
    alert('finished blinking');
}

$.fn.blinkOnce = function (duration, callback) {
    this.fadeTo(duration, 0).fadeTo(duration, 1, function () {
        if (typeof callback == 'function') callback.call(this);
    });
};

$.fn.blink = function (times, duration, callback) {
    var toBlink = this;
    var blinkComplete = function () {
        times--;
        if (times == 0) callback.call(this);
        else toBlink.blinkOnce(duration, blinkComplete);
    }

    toBlink.blinkOnce(duration, blinkComplete);
    return true;
};

http://jsfiddle.net/xgeLu/