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

て烟熏妆下的殇ゞ 提交于 2019-12-25 07:07:13

问题


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/


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/31887786/how-do-i-get-my-image-slider-to-reset-its-auto-scroll-timer-after-a-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!