AlbatrossCafe
AlbatrossCafe

Reputation: 1842

How do I get my image slider to reset its auto-scroll timer after a click?

I have an image slider with n amount of images. It scrolls automatically between each one every 5 seconds. There is a "previous" and "next" button on either side of the slider.

$('#button-next').click(function () {
    //goes to next slide
});
$('#button-prev').click(function () {
    //goes to previous slide
});

var _scrollInterval = AutoScroll();

function AutoScroll() {
    var temp = setInterval(function () {
        $('#button-next').click();
    }, 5000)

    return temp;
}

My desired functionality is that when the user clicks "next" or "previous", the AutoScroll() timer effectively "resets" back to 0 and then starts up again.

How can I accomplish this? I feel like I need to use clearInterval() or something along those lines but I am not too familiar with these functions.

Fiddle: https://jsfiddle.net/5u67eghv/4/

Upvotes: 0

Views: 994

Answers (3)

MazzCris
MazzCris

Reputation: 1840

This should work:

var temp;  // <- add variable declaration

$('#button-next').click(function () {
    nextImage = currentImage == lastImage ? firstImage : currentImage + 1;
    sliderImages.eq(currentImage).hide(500);
    sliderImages.eq(nextImage).show(500);
    currentImage = nextImage;

    clearInterval(temp);  // <- clear interval
    AutoScroll();         // <- restart autoscroll
});

$('#button-prev').click(function () {
    prevImage = currentImage == firstImage ? lastImage : currentImage - 1;
    sliderImages.eq(currentImage).hide(500);
    sliderImages.eq(prevImage).show(500);
    currentImage = prevImage;

    clearInterval(temp);  // <- clear interval
    AutoScroll();         // <- restart autoscroll
});

function AutoScroll() {
    temp = setInterval(function () { // <- temp variable already declared
        $('#button-next').click();
    }, 5000)
    return temp;
}

Upvotes: 1

code
code

Reputation: 1137

YOu need to clear your interval on each click of the button

$('#button-next').click(function () {
    //goes to next slide
    clearInterval(_scrollInterval);
    //Do other functions
    _scrollInterval = AutoScroll(); //Reset Interval Timer
});
$('#button-prev').click(function () {
    //goes to previous slide
     clearInterval(_scrollInterval);
    //Do other functions
    _scrollInterval = AutoScroll(); //Reset Interval Timer
});

var _scrollInterval = AutoScroll();

function AutoScroll() {
    var temp = setInterval(function () {
    $('#button-next').click();
}, 5000)

return temp;
}

Here you clear and reset interval every time button is pushed

Upvotes: 1

anam
anam

Reputation: 216

You are trying to clear the function not a variable try as follows: var myVar = setInterval(autoplay(), 5000); then clearInterval(myVar)

then set the interval again.

Upvotes: 0

Related Questions