2012-05-24 172 views
1

可能重复:
setTimeout in a for-loop and pass i as value的setTimeout在for循环不工作

我试图生成动态数组并使用此数组作为循环..但在循环时刻设定了不工作或功能不起作用。 这里是我的代码在功能removeClassImg

jQuery(document).ready(function() { 
    temp = new Array(); 
    generateArray(temp); 

    function generateArray(temp) { 
     if (temp.length < 10) { 
      res = randomXToY(1, 10, 0); 
      for (var k = 0; k < temp.length; k++) { 
       if (temp[k] == res) { 
        var test = 1; 
       } 
      } 
      if (test != 1) { 
       temp.push(res); 
       //abc(temp); 
      } 
      generateArray(temp); 
     } else { 
      for (var z = 0; z < 10; z++) { 
       tnest(temp[z]); 
       setTimeout(function() { 
        removeClassImg(temp[z]) 
       }, 3000); 
      } 
      temp = new Array(); 
      generateArray(temp); 
     } 
    } 

    function removeClassImg(result1) { 
     alert(result1); 
     $('#img' + result1).fadeTo(12000, 0.1); 
     return true; 
    } 

    function tnest(result) { 
     alert(result); 
     $('#img' + result).fadeTo(12000, 1); 
     return true; 
    } 

    function randomXToY(minVal, maxVal, floatVal) { 
     var randVal = minVal + (Math.random() * (maxVal - minVal)); 
     return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal); 
    } 
}); 

警报不工作..我使用的循环,这是不工作的罚款setTimeout的。

+0

你能给HTML代码吗?以便我们可以很好地解决您的问题 –

回答

4

它与超时和循环有关。您需要将其封装在闭包中,以便您的超时回调绑定到“当时”的值z

我也是在循环后发现这一点:

temp = new Array(); 
generateArray(temp); 

由你想操作的延迟操作的时间,你的阵列不包含您不再需要的值。你已经清除了它们。

试试这个:

for (var z = 0; z < 10; z++) { 
    (function (tz) {     //"localize" temp[z] by creating a scope 
     tnest(tz);     //that makes temp[z] local. this is done 
     setTimeout(function() {  //by creating an immediate function 
      removeClassImg(tz)  //passing temp[z] into it. that way, the 
     }, 3000);      //timeout receives a local temp[z] which 
    }(temp[z]));      //has the value of temp[z] "at that time" 
} 

这里的a sample with the closurea sample without it。 3秒后,你会看到没有它的人会记录所有10秒而不是0-10。

+0

仍然无法正常工作 –

+0

@harpreetkaur已更新。 – Joseph

2

那是因为你在你的setTimeout设置的功能访问变量z,创造了封闭,并z在循环使用。这意味着,当setTimeout调用该函数时,您可能最终有z等于10

我已经讨论过这个问题,在这里可能的解决方案:How to pass a variable into a setTimeout function?我认为这将帮助你!