artparks
artparks

Reputation: 761

jquery each() with setInterval

I have an object filled with various elements that I wish to iterate through using each() and then perform an action on the element whose turn it is. So:

var arts = $("#press-sqs > article");
shuffle(arts);

$(arts).each(function(){
    setInterval(function() {
    // in here perform an action on the current element in 'arts'
    }, 2000);   
}); 

( shuffle() is a basic shuffle function )

What I can't figure out is how to access the current element as a selector and perform an action on it. $(this) is $(window).

Finally I would then need the function to start the iteration again once it reaches the end of art and keep on looping ad infinitum.

Upvotes: 4

Views: 16310

Answers (3)

Eric
Eric

Reputation: 97571

If you're using setInterval, you'd get identical results swapping the order:

setInterval(function() {
    $(arts).each(function(){
         doSomethingWith(this);
    });   
}, 2000);

I don't think you want what you think you do here. I reckon you want:

var i = 0;
setInterval(function() {
    var art = arts[i++];
    doSomethingWith(art)
    if(i >= arts.length) i = 0;
}, 2000); 

Upvotes: 9

Will Palmer
Will Palmer

Reputation: 5952

jQuery's .each(...) method passes the "current" element (and its index) into the callback. this is just a convenience for when you don't need to do anything too complicated.

$(arts).each(function(i, current){
    setInterval(function() {
    // in here perform an action on the current element in 'arts'
    }, 2000);   
});

Above, the current element is available within the setInterval callback as current, for example. Note that this element is passed in its "raw" form, as this is, so if you want to call jQuery methods on it, you'll need to wrap it in the same way, ie: $(current).

Upvotes: 4

Vlad
Vlad

Reputation: 2565

Use that.

$(arts).each(function(){
    var that = this;
    setInterval(function() {
    // in here perform an action on the current element in 'arts'
         doSomethingWith(that)
    }, 2000);   
});

Upvotes: 2

Related Questions