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

1 个解决方案

#1


9

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. 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:

这些情况似乎最好通过将操作放入本地函数然后从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();
      });
});

更多相关文章

  1. 传递变量以便以角度移动子弹
  2. 如何将变量推送到web客户端以获取ajax?
  3. 运行一次后停止执行函数
  4. Javascript日期/时间函数是否依赖于客户端机器?
  5. js学习之路2: JavaScript 变量
  6. 是否可以从节点js中的同一模块导出构造函数和一些正常函数?
  7. javaES6箭头函数的全新特性
  8. JavaScript学习-5——异步同步、回调函数
  9. 让Heroku的配置变量在node.js中工作

随机推荐

  1. docker为何选择golang开发?
  2. golang不规则json解析
  3. golang recover后怎么返回
  4. golang不定长参数写法
  5. go和golang之间有区别吗?
  6. golang read会阻塞么
  7. golang并发不是并行
  8. golang panic可以捕获标准错误吗
  9. golang和c语言的区别是什么?
  10. golang中vendor什么时候进来的