user2054689
user2054689

Reputation: 27

How to add .delay to .click on .each iteration (jquery)

So, I want to put delay on this JavaScript code.

$(function(){ 
     $('.clickThis').each(function(){ 
         $(this).click();
     }); 
});

I tried this

$(function(){ 
     $('.clickThis').each(function(){
         $(this).click().delay(5000); 
     }); 
});

above script doesnt work .

Is there any alternative?

I've tried Google it but I still couldn't figure it out, because I have little knowledge in JavaScript.

Upvotes: 3

Views: 2877

Answers (7)

dlock
dlock

Reputation: 9577

Try

$(function(){ 
     $('.clickThis').each(function(_,i){ 
        var me=$(this);
        setTimeout(function(){me.click()},5000*i);
     ); 
});

Upvotes: -3

Alnitak
Alnitak

Reputation: 339955

Here's a version using a recursive setTimeout loop.

$(function() {
    var click = $('.clickThis').toArray();

    (function next() {
        $(click.shift()).click();   // take (and click) the first entry
        if (click.length) {         // and if there's more, do it again (later)
            setTimeout(next, 5000);
        }
    })();
});

The advantage of this pattern over setTimeout(..., 5000 * i) or a setInterval call is that only a single timer event is ever queued at once.

In general, repeated calls to setTimeout are better than a single call to setInterval for a few reasons:

  1. setInterval calls can queue up multiple events even if the browser isn't active, which then all fire as quickly as possibly when the browser becomes active again. Calling setTimeout recursively guarantees that the minimum time interval between events is honoured.
  2. With setInterval you have to remember the timer handle so you can clear it

Upvotes: 5

mikakun
mikakun

Reputation: 2265

var $clickthis=$(".clickthis");
var i= -1;
var delayed = setInterval(function(){
 if (++i < $clickthis.length) $clickthis.eq(i).trigger("click");
 else clearInterval(delayed);
}, 5000);

Upvotes: 0

Ruslan Polutsygan
Ruslan Polutsygan

Reputation: 4461

Try to use this:

$(function () {
    var items=$('.clickThis');
    var length=items.length;
    var i=0;
    var clickInterval=setInterval(function(){
        items.eq(i).click();
        i++;
        if(i==length)
            clearInterval(clickInterval);
    }, 5000);
});

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196207

This will do it:

$(function(){ 
    $('.clickThis').each(function(i, that){ 
        setTimeout(function(){
            $(that).click();
        }, 5000*i );
    }); 
});

Upvotes: 9

Roger C
Roger C

Reputation: 305

You need to write an asynchronous setTimeout loop, for more information http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/

Upvotes: 0

Mickael
Mickael

Reputation: 5736

I am not sure but I think that setTimeout function should do the trick. See here https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout

Upvotes: -1

Related Questions