elzi
elzi

Reputation: 5672

jquery combining each and setInterval on elements with shared class

I have a series of links with a class "bloglink".

They have a click event associated with them - but that is irrelevant at this point. I am trying to cycle through them and trigger the click event every X seconds. This is where I'm at:

$('a.bloglink').each(function(){
    var $bl = $(this);
    setInterval(function(){
        $bl.trigger('click')
    },2000);
})

But it just triggers the click event for all of them at once.

Any tips?

Upvotes: 1

Views: 601

Answers (2)

skeelsave
skeelsave

Reputation: 178

Create a function that sets the timer to run your code, clears the timer, then calls itself on the next element...

function processNext($current)
{
    $h = setInterval(function() {
        $current.css('color', 'green');//do your business here
        clearTimeout($h);
        if ($current.next('a.blah').size()>0)
        {
            processNext($current.next('a.blah'));
        }
    }, 750);
}
processNext($('a.blah').eq(0));

See here: http://jsfiddle.net/skeelsave/6xqWd/2/

Upvotes: 0

Shmiddty
Shmiddty

Reputation: 13967

You could do something like this:

(​function Loop()​{
    var arry = $("a.bloglink").get();
    var traverse = function(){
        $(arry.shift()).trigger('click');

        if (arry.length)
            setTimeout(traverse, 2000);
    };
    setTimeout(traverse,2000);
})();

You can see it in action here: http://jsfiddle.net/Shmiddty/B7Hpf/

To start it over again, you can just add an else case:

(​function Loop()​{
    var arry = $("a.bloglink").get();
    var traverse = function(){
        $(arry.shift()).trigger('click');

        if (arry.length)
            setTimeout(traverse, 2000);
        else
            Loop(); // Do the whole thing again
    };
    setTimeout(traverse,2000);
})();

See here: http://jsfiddle.net/Shmiddty/B7Hpf/1/

Upvotes: 2

Related Questions