Search code examples
javascriptjqueryiterationdelay

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.


Solution

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