jQuery setTimeOut while循环 [英] JQuery setTimeOut while loop
问题描述
我的大脑会爆炸..为什么这不起作用?我试图以时间间隔为一些div设置动画,并尝试编写更少的代码,但这不起作用
My brain its going to explode.. why this dont work? im trying to animate a few divs with time interval and trying to write less code but this dont work
var cargaCont = function(){
o = 1;
var animacion = function(i){
$('#page2txt'+i).animate({
height:'20'
},200,function(){
$('#page2img'+i).animate({
left:'0',
right:'0'
},200,function(){
i++;
return i;
});
});
}
while(o < 3){
setTimeout(function(){o = animacion(o);},200);
}
}
推荐答案
此代码存在问题:
while(o < 3){
setTimeout(function(){o = animacion(o);},200);
}
是在执行被setTimeout
延迟的功能时,o
已经是3,因此对animacion
的所有调用都传递3而不是1和2.
is by the time the functions delayed by setTimeout
are executed, o
is already 3 and therefore all calls to animacion
pass 3 instead of 1 and 2.
要避免此问题,应使用立即函数将"o
"的值本地化".
To circumvent this problem, you should "localize" the value of o
by using an immediate function.
while(o < 3){
//o out here is from cargaCont
(function(o){
//override o by naming the passed variable o
setTimeout(function(){
o = animacion(o); //now o refers to the local o
},200);
}(o)); //execute inner function, passing in o
}
这使得setTimeout
中的功能使用的o
绑定到本地功能的o
而不是cargaCont
功能的o
.
This makes the o
used by the functions in setTimeout
to be bound to the o
of the local function and not the o
of the cargaCont
function.
这篇关于jQuery setTimeOut while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!