JQuery - How to loop a function?

I want to make a basic fadein fadeout slideshow. I only make it automatically start once. How do I make it have a loop?

Html

<img src="image1.jpg" class="img1">
<img src="image2.jpg" class="img2">

      

Js

$(document).ready(function () {
function playslider(){
        $('.img1').fadeIn(800).delay(800).fadeOut(800);
        $('.img2').delay(1600).fadeIn(800).delay(800).fadeOut(800);
}   
playslider();
});

      

+3


source to share


4 answers


Try changing it to this:

$(document).ready(function () {
function playslider(){
        $('.img1').fadeIn(800).delay(800).fadeOut(800);
        $('.img2').delay(1600).fadeIn(800).delay(800).fadeOut(800, playslider);
                                                                 //^callback function
}   
playslider();
});

      



This is called a "callback function". The idea is that it gets called when your last completion completes. You can read it here .

+7


source


You can use good old Javascript:



 $(document).ready(function () {
 function playslider(){
      // code to execute
     x = setTimeout("playslider()", 5000); //will loop every 5 seconds.
 }   
 playslider(); //start it up the first time

 });

      

+2


source


Answer:

$(document).ready(function () {
 function playslider(){
      // code to execute
     x = setTimeout(function(){playslider()}, 5000);
 }   
 playslider();

 });

      

+2


source


it works well but if u change it that way it works better

    $('.img1').fadeIn(800).delay(800).fadeOut(800);
    $('.img2').delay(2400).fadeIn(800).delay(800).fadeOut(800, playslider);

      

just increase the dalay time to 2400 (2400 = 800 + 800 + 800)

0


source







All Articles