简体   繁体   中英

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/

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM