Jquery setInterval function

$(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 has a class called active, which means it is being displayed.

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

However, when the page loads, the function only works once, and not cyclically.

Any ideas?

+6
source share
5 answers

This is because you are executing a function that does not reference it. You must do:

  setInterval(swapImages,1000); 
+17
source

Do not pass the result of swapImages to setInterval , calling it. Just pass a function, for example:

 setInterval(swapImages, 1000); 
+4
source

// 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); }); 
+2
source

try this to declare a function outside the finished 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'); } 
+1
source

You can use it as follows:

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

});

-1
source

Source: https://habr.com/ru/post/892747/


All Articles