jQuery setTimeOut while循环 [英] JQuery setTimeOut while loop

查看:166
本文介绍了jQuery setTimeOut while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的大脑会爆炸..为什么这不起作用?我试图以时间间隔为一些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 setTimeoutto be bound to the o of the local function and not the o of the cargaCont function.

这篇关于jQuery setTimeOut while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆