如何在重新调用函数之前等待动画完成

时间:2015-11-28 00:38:57

标签: javascript jquery

我使用递归来多次重复一个函数。每次运行该函数时,都会出现持续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);

}

1 个答案:

答案 0 :(得分:3)

你应该使用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);
          });
    }
}