简体   繁体   English

将循环的每次迭代延迟一定时间

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

JSFiddle: http://jsfiddle.net/KH8Gf/27/ JSFiddle: http //jsfiddle.net/KH8Gf/27/

Code: 码:

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

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

How can I delay each iteration of the loop by a certain time? 如何将循环的每次迭代延迟一定时间?

I tried the following unsuccessfully: 我尝试了下面的失败:

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

and

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

These cases all seem to work best by putting the operation into a local function and then calling that local function from setTimeout() to implement your delay. 这些情况似乎最好通过将操作放入本地函数然后从setTimeout()调用该本地函数来实现延迟。 Due to the wonders of closures in javascript, the local function gets access to all the variables at the levels above it so you can keep track of your loop count there like this: 由于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