سؤال

Code

I need help making callback after all animate methods inside do_animations are done. For one animate i could call promise and done function. I tried using $.Callbacs but i don't know how to make promise object from fire method.

function random_num(a, b) {
    return Math.floor(Math.random() * (b - a + 1)) + a;
}

function do_animations() {
    var n = random_num(1, 5);
    for (var i = 0; i < n; i++) {
        var width = random_num(-50, 50);
        $('#rec').animate({'left': '+=' + width + 'px'}, 300);
    }
}

$(document).ready(function(){
    do_animations();
});

Best solution would be

do_animations().done(function(){ ... });
هل كانت مفيدة؟

المحلول

Using promise():

DEMO

function do_animations() {
    var n = random_num(1, 5),
        $rec = $('#rec');
    for (var i = 0; i < n; i++) {
        var width = random_num(-50, 50);
        $rec.animate({'left': '+=' + width + 'px'}, 300);
    }
    return $rec.promise();
}

$(document).ready(function(){
    do_animations().done(function(){ alert("All animations done!") });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top