简体   繁体   中英

add a short delay between each iteration of do while loop

I have written a code to trigger click event on the four labels on my page and the loop is working fine as i tested it using alert box written in loop body. but by default, in jquery all iterations happen so quick that it is impossible to see those click events happening.

so I want to add a short delay in the do while loop. Loop that i have written is:

var elets = $('label');
var n = elets.length;
var i=0;
do
{
    //setTimeout ( function() {
    var forname = elets[i].getAttribute("for");
    var selected_label = $('label[for='+forname+']');
    selected_label.trigger("click");
    i++;
    //}, 3000);
} while(i<n)

I also want this loop to be repeated continuously.

The simplest solution is to use setTimeout . With an immediately invoked named function, the code can be about as simple and clear as with a do or for loop :

var elets = $('label');
var n = elets.length;
var i=0;
(function doOne(){
    var forname = elets[i].getAttribute("for");
    var selected_label = $('label[for='+forname+']');
    selected_label.trigger("click");
    if (i++<n) setTimeout(doOne);
})();

you can also use .delay() function

refer http://api.jquery.com/delay/

for example :

<script>
   $( "button" ).click(function() {  
      $( "div.first").delay( 800);
   });

Here div first will be loade after interval of 800 milliseconds once click on button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM