JQuery setTimeOut while loop

前提是你 提交于 2019-12-13 06:05:55

问题


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);
        }   
    }

回答1:


The problem with this code:

while(o < 3){
    setTimeout(function(){o = animacion(o);},200);
} 

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.

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
} 

This makes the o used by the functions in setTimeoutto be bound to the o of the local function and not the o of the cargaCont function.




回答2:


I'm not 100% sure what exactly you're going for but, I'm going to guess that you basically want to loop through some animations, maybe like this:

var cargaCont = function(){
    var i = 1,
        animacion = function(i){
            $('#page2txt'+i).animate({
               height:'20'
           },200,function(){
               $('#page2img'+i).animate({
                   left:'0',
                   right:'0'
               },200,function(){
                   if(i < 3){
                      animacion(++i);
                   }
               });
           });
       };
    animacion(i);
};

Edit as you feel fit or post some markup to explain further.

Cheers.



来源:https://stackoverflow.com/questions/11555611/jquery-settimeout-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!