0
$(function(){
    $('.fadein img:gt()').hide();
    setInterval(function(){
      $('.fadein :first-child').fadeOut()
         .next('img').fadeIn()
         .end().appendTo('.fadein');}, 
      6800);
});

I'm hoping to stop this onclick of a button and start it on click of same button. any ideas?

khr055
  • 28,690
  • 16
  • 36
  • 48

1 Answers1

1

Try this:

$(function(){
    $('.fadein img:gt()').hide();
    var active = true;
    setInterval(function(){
      if(active) {
        $('.fadein :first-child').fadeOut()
           .next('img').fadeIn()
           .end().appendTo('.fadein');
      }
    }, 6800);

    $('#buttonId').click(function(){ active = !active; });
});

Thanks to Rikonator, here is better answer:

$(function(){
    $('.fadein img:gt()').hide();
    var active = true;
    var interval = setInterval(intervalFunction, 6800);

    $('#buttonId').click(function(){ 
       if(!active) 
          interval = setInterval(intervalFunction, 6800)
       else
          clearInterval(interval);
    });

    function intervalFunction(){
        $('.fadein :first-child').fadeOut()
           .next('img').fadeIn()
           .end().appendTo('.fadein');
    }
});
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • I'm curious; wouldn't clearing the interval on stop and setting it again on start be better? If it is stopped for a long time, won't the function be called unnecessarily after each interval? – Rikonator Dec 26 '12 at 18:17
  • see this answer, I think it's what you need: http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript – karaxuna Dec 26 '12 at 18:25
  • I meant in reference to your answer. Wouldn't clearing the interval on stop and setting it back again on start in the `click` function be better performance-wise, as compared to simply toggling a flag? As it is, you allow the interval function to be called even when it is 'stopped', which is unnecessary seeing as the function does nothing when `active` is false. – Rikonator Dec 26 '12 at 18:33
  • ohhh, thats pretty close. the images flash one at a time as they load since they are all positioned on top of each other. But the button works great thanks a bunch! – user1843261 Dec 26 '12 at 18:39