Reputation: 138
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.
Upvotes: 3
Views: 2167
Reputation: 305
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.
Upvotes: 0
Reputation: 382474
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);
})();
Upvotes: 4