Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay each iteration of loop by a certain time

JSFiddle: http://jsfiddle.net/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'); 
like image 842
xbonez Avatar asked Dec 29 '11 07:12

xbonez


People also ask

What is a time delay loop?

Time delay loops are often used in programs. These are loops that have no other function than to kill time. Delay loops can be created by specifying an empty target statement.

How do you delay a loop in Python?

For adding time delay during execution we use the sleep() function between the two statements between which we want the delay.

How do you wait for loop to finish?

To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop.


1 Answers

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();
      });
});
like image 89
jfriend00 Avatar answered Oct 03 '22 06:10

jfriend00