admin管理员组文章数量:1356860
JSFiddle: /
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');
JSFiddle: http://jsfiddle/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');
Share
Improve this question
asked Dec 29, 2011 at 7:16
AyushAyush
42.4k51 gold badges168 silver badges241 bronze badges
1 Answer
Reset to default 9These 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();
});
});
本文标签: javascriptDelay each iteration of loop by a certain timeStack Overflow
版权声明:本文标题:javascript - Delay each iteration of loop by a certain time - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743956277a2568188.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论