Jaaaaaaay
Jaaaaaaay

Reputation: 1975

Jquery, Click to kill a function

I'm trying to create a slider with three slides. Originally, the slides will display as a loop. My goal is, if a button like #fancy_1 is clicked, the loop with a function name "runem" will be stopped and the loop just ends there. I tried put a stop(true,true), but with no success. No matter whether the button is clicked or not, the loop is always running. Does anyone have any idea how to achieve this?

(function($) {
  $(document).ready(function() {
    function runem() {
      var allofEm = $('.j_fancy .j_fancy_block');
      var $active = allofEm.eq(0);
      $active.show();
      var $next = $active.next();
      var timer = setInterval(function() {
        $next.fadeIn();
        $active.hide();
        $active = $next;
        $next = (allofEm.last().index() == allofEm.index($active)) ?
          $next = allofEm.eq(0) : $active.next();
      }, 5000);
    }
    runem();

    $("#fancy_1").click(function() {
      $('.j_fancy_block').eq(0).show();
      $('.j_fancy_block').eq(1).hide();
      $('.j_fancy_block').eq(2).hide();
      runem().stop(true, true); //this doesn't work. 
    })

    $("#fancy_2").click(function() {
      $('.j_fancy_block').eq(0).hide();
      $('.j_fancy_block').eq(1).show();
      $('.j_fancy_block').eq(2).hide();
      runem().stop(true, true); //this doesn't work. 
    })


    $("#fancy_3").click(function() {
      $('.j_fancy_block').eq(0).hide();
      $('.j_fancy_block').eq(1).hide();
      $('.j_fancy_block').eq(2).show();
      runem().stop(true, true); //this doesn't work. 
    })

  })

}(jQuery));

Upvotes: 0

Views: 521

Answers (1)

Adjit
Adjit

Reputation: 10305

Have you tried using clearInterval()? The reason that stop() was not working is because that is a function to stop jQuery animations, not Javascript setInterval - so setInterval will continue to run

The way I would suggest using it is like so...

var boxInterval;

function runem(){
    /*Function Stuff*/
    boxInterval = setInterval(function(){...});
}

function stopBox(){
    clearInterval(boxInterval);
}

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval#Example

Upvotes: 5

Related Questions