18
$(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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
callum.bennett
  • 678
  • 3
  • 12
  • 28

5 Answers5

42

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

  setInterval(swapImages,1000);
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
15

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

setInterval(swapImages, 1000);
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
4

// 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);
});
phemt.latd
  • 1,775
  • 21
  • 33
Rajkumar
  • 51
  • 1
-1

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);
}

});

ashvagan
  • 43
  • 2
  • 8
-1

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');
}
zevy_boy
  • 902
  • 1
  • 7
  • 11
  • This has nothing to do with the problem. The function will still execute once, when the DOM's ready event fires and not every 1000 ms from that point on. – Matey Yanakiev Dec 04 '12 at 00:19