在JQuery动画循环中,在所有动画完成后运行函数

时间:2014-05-08 15:39:35

标签: javascript jquery loops jquery-animate

我有一个循环,通过将值作为数组来动画16个不同的元素。那部分有效,它目前正常动画。

我希望在每个动画完成后调用一个函数。

//loop through the grid
    for (var y = 0; y < grid.length; y++) {
        for (var x = 0; x < grid[y].length; x++) {

            //if its not an empty space
            if (grid[y][x].type != 0) {

                $('#ent'+grid[y][x].entNum).animate({
                    left: (x*16*zoom)+'px',
                    top: ((1+(+y))*16*zoom)+'px'
                },{duration: 100,queue:false,complete:function(){ //end of animation
                    //doesn't really work here
                    okayToMove = true;
                }});

            }
        }
    }

你可以看到我想在动画结束后设置okayToMove = true,但是正如我目前所拥有的那样,它会将该变量设置为16次,并且在第一次变量完成后它将为真,而不是最后一个。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用jQuery $。延期

来实现这一目标
var deferreds = [];


//loop through the grid
    for (var y = 0; y < grid.length; y++) {
        for (var x = 0; x < grid[y].length; x++) {

            //if its not an empty space
            if (grid[y][x].type != 0) {
                var def = new $.Deferred();    
                deferreds.push(def);
                (function(defferdToResolve){
                   $('#ent'+grid[y][x].entNum).animate({
                    left: (x*16*zoom)+'px',
                    top: ((1+(+y))*16*zoom)+'px'
                    },{duration: 100,queue:false,complete:function(){ //end of animation
                    //doesn't really work here
                    defferdToResolve.resolve();
                    }});
                })(def);


            }
        }
    }

这将是解决所有承诺的处理程序(即所有动画都会调用回调)。

$.when.apply($, deferreds).done(function(){
  alert('All animations are done at this point!');
});

为了说明$。更好地推荐codepen

答案 1 :(得分:1)

如何使用计数器来制作动画数量

var animations = 0;
for (var y = 0; y < grid.length; y++) {
    for (var x = 0; x < grid[y].length; x++) {

        //if its not an empty space
        if (grid[y][x].type != 0) {

            animations++;
            $('#ent'+grid[y][x].entNum).animate({
                left: (x*16*zoom)+'px',
                top: ((1+(+y))*16*zoom)+'px'
            },{duration: 100,queue:false,complete:function(){ //end of animation
                //doesn't really work here
                animations--;
            }});

        }
    }
}

每次动画开始时,计数器都会递增,并且在每个动画的回调中,计数器会递减。这样,一旦第一个动画开始,你就可以监视计数器的值,当它再次达到0时,你知道最后一个动画已经完成。