2011-12-29 130 views
6

的jsfiddle每次循环:http://jsfiddle.net/KH8Gf/27/延迟经一定时间

代码:

$(document).ready(function() 
{ 
$('#expand').click(function() 
    { 
     var qty= $('#qty').val(); 

     for (var counter = 0; counter < qty; counter++) 
     { 
      $('#child').html($('#child').html() + '<br/>new text');    
     } 
    }); 
}); 

我如何通过一定的时间延迟每次循环?

我尝试以下失败:

setTimeout(function(){ 
$('#child').html($('#child').html() + '<br/>new text'); 
},500); 

$('#child').delay(500).html($('#child').html() + '<br/>new text'); 

回答

9

这些案件似乎都通过将操作到本地功能,然后调用从setTimeout()本地函数来实现最好的工作你的延迟。由于关闭的JavaScript中的奇观,当地的功能得到在它上面的级别的访问所有的变量,所以你可以跟踪你的循环计数有这样的:

$(document).ready(function() { 
    $('#expand').click(function() { 
      var qty = $('#qty').val(); 
      var counter = 0; 
      var child = $('#child'); 

      function next() { 
       if (counter++ < qty) { 
        child.append('<br/>new text');    
        setTimeout(next, 500); 
       } 
      } 
      next(); 
     }); 
}); 
+2

你应该将'的setTimeout(接下来, 500);进入if块。 – 2011-12-29 07:21:28

+2

@JosephSilber - 更正 - thx。尝试输入速度太快(竞赛张贴在SO这对我来说)。 – jfriend00 2011-12-29 07:25:05

+0

@ jfriend00 +1和它的工作。我甚至没有完成中途输入:( – gideon 2011-12-29 07:27:07