1

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.

1

3 Answers 3

3

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks for that man, that is the code I wanted to write, thanks for not only answering my question but showing me what cleaner code looks like.
1

Store the result of setInterval in a variable.

Then use clearInterval to stop it.

2 Comments

Would it need to be a global variable?
Doesn't necessarily have to be global, but it needs to be outside the scope of your slider function to be accessible from your click handler.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.