[英]How to wait until an animation is completed before re-calling a function
I'm using recursion to repeat a function multiple times. 我正在使用递归多次重复一个函数。 Each time the function is run, an animation lasting 600 milliseconds will occur, so I'm trying to use setTimeout to delay re-calling the function so that it won't be re-called until the animation has completed. 每次运行该函数时,都会出现持续600毫秒的动画,因此,我尝试使用setTimeout延迟重新调用该函数,以便在动画完成之前不会重新调用该函数。 For some reason what I have is resulting in some weird stuff: Using my inspector I can see that the function is running and all the appropriate values are changing, but the new values never get rendered. 由于某种原因,我得到的东西有些奇怪:使用检查器,我可以看到该函数正在运行并且所有适当的值都在更改,但是新值从未被渲染。
If anyone has any other suggestions for how to wait until an animation is completed before repeating the function, that would also do! 如果有人对重复动画之前如何等待动画完成还有其他建议,那也可以! Thanks in advance! 提前致谢!
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);
}
You should use the function callback offered by jQuery's .animate()
http://api.jquery.com/animate/ 您应该使用jQuery的.animate()
http://api.jquery.com/animate/提供的函数回调
var run_program = function() {
$( ".reader" ).animate({
left: "+=50"
}, 600, function() {
// Do something after the Animation is complete.
});
}
Another method would be to get rid of the for loop all together, and in your recursive call just increment the index. 另一种方法是一起消除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);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.