Delay each iteration of the loop for a specific time

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

The 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 postpone each iteration of a loop for a specific 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'); 
+6
source share
1 answer

All of these cases work best by putting the operation in a local function, and then calling this local function from setTimeout() to realize your delay. Thanks to the miracles of closure in javascript, a local function gains access to all variables at the levels above so that you can track the number of loops, for example:

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

Source: https://habr.com/ru/post/904649/


All Articles