Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 572
artparks Avatar asked Dec 07 '22 12:12

artparks


2 Answers

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); 
like image 119
Eric Avatar answered Dec 11 '22 09:12

Eric


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).

like image 37
Will Palmer Avatar answered Dec 11 '22 10:12

Will Palmer