thesteve
thesteve

Reputation: 2503

Stopping a running function in javascript/jquery on click event

I have a slideshow function in jquery that I want to stop on a particular click event. The slideshow function is here:

function slider(){
   setInterval(function(){
   var cur = $('img.active');
   cur.fadeOut('fast');
   cur.removeClass('active');
   cur.css('opacity','0');
   cur.addClass("hidden");
   var nextimg;
   if (!cur.hasClass("last")){
     nextimg = cur.next("img");
     }
   else {
     nextimg = cur.prev().prev().prev();
  }
   nextimg.removeClass("hidden").fadeIn('slow').css('opacity','1').addClass('active');
  },5000);
 }

I have been reading about .queue but not sure how I can use it exactly, can I call my function from a queue and then clear the queue on a click event? I cannot seem to figure out the syntax for getting it to work of if thats even possible. Any advice on this or another method to stop a running function on a click would be appreciated.

Upvotes: 1

Views: 10271

Answers (3)

Kevin Ennis
Kevin Ennis

Reputation: 14456

For what it's worth, it's generally advisable to use a recursive setTimeout instead of a setInterval. I made that change, as well as a few little syntax tweaks. But this is a basic implementation of what I think you want.

// Store a reference that will point to your timeout
var timer;

function slider(){
    timer = setTimeout(function(){
        var cur = $('img.active')
                .fadeOut('fast')
                .removeClass('active')
                .css('opacity','0')
                .addClass('hidden'),
            nextimg = !cur.hasClass('last') ? cur.next('img') : cur.prev().prev().prev();
        nextimg.removeClass('hidden')
            .fadeIn('slow')
            .css('opacity','1')
            .addClass('active');
        // Call the slider function again
        slider();
    },5000);
 }

$('#someElement').click(function(){
    // Clear the timeout
    clearTimeout(timer);
});

Upvotes: 3

ExpExc
ExpExc

Reputation: 3926

Store the value returned by setInterval, say intervalId to clear it, your click handler should look like this:

function stopSlider() {
    //prevent changing image each 5s
    clearInterval(intervalId);
    //stop fading the current image
    $('img.active').stop(true, true);
}

Upvotes: 1

Steve Wellens
Steve Wellens

Reputation: 20620

Store the result of setInterval in a variable.

Then use clearInterval to stop it.

Upvotes: 1

Related Questions