将循环的每次迭代延迟一定时间 [英] Delay each iteration of loop by a certain time

查看:129
本文介绍了将循环的每次迭代延迟一定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

How can I delay each iteration of the loop by a certain time?

我尝试了下面的失败:

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

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


推荐答案

通过操作这些案例看起来效果最好进入本地函数,然后从 setTimeout()调用该本地函数来实现延迟。由于javascript中的闭包奇迹,本地函数可以访问其上面的所有变量,因此您可以像这样跟踪您的循环计数:

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:

$(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();
      });
});

这篇关于将循环的每次迭代延迟一定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆