簡體   English   中英

將循環的每次迭代延遲一定時間

[英]Delay each iteration of loop by a certain time

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

這些情況似乎最好通過將操作放入本地函數然后從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();
      });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM