callum.bennett
callum.bennett

Reputation: 686

jquery function setInterval

$(document).ready(function(){

    setInterval(swapImages(),1000);

    function swapImages(){

        var active = $('.active'); 
        var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');

        active.removeClass('active');
        next.addClass('active');
    }
});

I have 13 images contained in a div. The first one has a class called active, which means it is displayed.

The swap images function selects the active image and hides it, and makes the next image active.

However, when the page loads, the function only works correctly once, rather than looping.

Any ideas?

Upvotes: 18

Views: 136892

Answers (6)

This is what you need

setInterval(function() { alert("Haha"); }, 1000);

Upvotes: 2

Rajkumar
Rajkumar

Reputation: 51

// simple example using the concept of setInterval

$(document).ready(function(){
var g = $('.jumping');
function blink(){
  g.animate({ 'left':'50px' 
  }).animate({
     'left':'20px'
        },1000)
}
setInterval(blink,1500);
});

Upvotes: 4

zevy_boy
zevy_boy

Reputation: 900

try this declare the function outside the ready event.

    $(document).ready(function(){    
       setInterval(swapImages(),1000); 
    });


    function swapImages(){

    var active = $('.active'); 
    var next = ($('.active').next().length > 0) ? $('.active').next() :         $('#siteNewsHead img:first');
    active.removeClass('active');
    next.addClass('active');
}

Upvotes: -1

FishBasketGordo
FishBasketGordo

Reputation: 23142

Don't pass the result of swapImages to setInterval by invoking it. Just pass the function, like this:

setInterval(swapImages, 1000);

Upvotes: 16

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

This is because you are executing the function not referencing it. You should do:

  setInterval(swapImages,1000);

Upvotes: 44

ashvagan
ashvagan

Reputation: 43

You can use it like this:

$(document).ready(function(){

    setTimeout("swapImages()",1000);

    function swapImages(){

        var active = $('.active'); 
        var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');

        active.removeClass('active');
        next.addClass('active');
        setTimeout("swapImages()",1000);
}

});

Upvotes: -1

Related Questions