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

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() + '
new text'); } }); });

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

我尝试了下面的失败:

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

 $('#child').delay(500).html($('#child').html() + '
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('
new text'); setTimeout(next, 500); } } next(); }); });