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