【问题标题】:How to wait until an animation is completed before re-calling a function如何在重新调用函数之前等到动画完成
【发布时间】:2015-11-28 09:02:13
【问题描述】:

我正在使用递归多次重复一个函数。每次运行该函数时,都会出现一个持续 600 毫秒的动画,因此我尝试使用 setTimeout 来延迟重新调用该函数,以便在动画完成之前不会重新调用它。出于某种原因,我得到了一些奇怪的东西:使用我的检查器,我可以看到函数正在运行并且所有适当的值都在变化,但新值永远不会被渲染。

如果有人对如何等到动画完成再重复该功能有任何其他建议,那也可以!提前致谢!

var run_program = function() {

    for (var j=0; j< program.length; j++) {    //loops through the different lines of turingcode

        if (reader.state === program[j].state && reader.scanning === program[j].scanning) { //if there is a line of turingcode for the readers current state and scanning values.

            cellArray[reader.location].content = program[j].print; //change the content of the current cell to the new value

            reader.location += 1; //increase the value of the reader's location

            $(".reader").animate({"left":"+=50px"}, 600); //move the div to the right so it appears to be under the next cell

            reader.scanning = cellArray[reader.location].content; //update the readers scanning value to be the value of the new cell

            reader.state = program[j].next_state; // update the state of the reader to that specified by the line of turingcode

            break;

        }

        else if (j === $scope.program.length-1) { //if there is no line of turingcode for the readers current state and scanning values, and j has looped through the entire list of turingcode lines

            return;  //halt the function

        }

    }

    setTimeout(run_program, 600);

}

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你应该使用jQuery的.animate()http://api.jquery.com/animate/提供的回调函数

    var run_program = function() {
      $( ".reader" ).animate({
        left: "+=50"
      }, 600, function() {
        // Do something after the Animation is complete.
      });
    }
    

    另一种方法是完全摆脱 for 循环,并在递归调用中增加索引。

    var run_program = function(var index) {
        if(typeof index === "undefined") {
            //this means it is the first time the function is being run (ie run_program())
            index = 0;
        }
    
        if (index < program.length) {
            //haven't reached the bounds of the initial for loop
            //run your other function checks
    
            $('.reader').animate({
                left: "+=50"
              }, 600, function() {
                   run_program(index+1);
              });
        }
    }
    

    【讨论】:

    • 我试过了,但似乎发生的情况是,当我的回调函数等待被调用时,for 循环继续循环,给我带来了问题。
    • 好吧,所以我认为另一种选择是将索引变量传递给函数并摆脱for 循环。然后在每次回调之前增加索引并再次将其传递给函数。从而摆脱你的 for 循环问题。我会发布更多详细信息。
    • @snookieordie 查看我的编辑,了解如何避免 for 循环问题的详细信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2010-11-07
    • 2017-03-15
    • 2018-07-14
    • 1970-01-01
    • 2016-11-29
    相关资源
    最近更新 更多