如何在调用clearInterval后再次启动setInterval

时间:2018-06-15 11:33:08

标签: jquery setinterval

我想要实现的目标

您好,我正在尝试创建一个基本滑块,滑块应该每10秒自动滑动一次,但是当用户单击下一个幻灯片按钮(.next)时,我希望它滑动到下一张幻灯片并重置setInterval计时器从点击

开始10秒

目前正在做什么

此时它会自动滑动,但是一旦单击下一个按钮,它就会停止setInterval而不是重置setInterval计时器

var slideTimer;
var slideTimer = setInterval(nextSlide, 3000);


$(".next").click(function(){
    nextSlide();
});

function nextSlide() {
    $(".sliders img:first").appendTo(".sliders"); 
    $(".next").click(function(){
    clearInterval(slideTimer);
    });
};

3 个答案:

答案 0 :(得分:2)

如果你想暂停10秒钟,那么你可以试试这个:

// var slideTimer; // don't need this as you declare it below
var slideTimer = setInterval(nextSlide, 3000); // start slide show


$(".next").click(function(){
    clearInterval(slideTimer);  // clear the interval
    nextSlide();                // show the next slide
    setTimeout(function() {
      slideTimer = setInterval(nextSlide, 3000); 
    },7000); // start the interval in 7 seconds which will show in 10 seconds (3000+7000)
});

function nextSlide() {
    $(".sliders img:first").appendTo(".sliders"); // only need to append in this - don't need to rebind
};

如果您只想让间隔在10秒内恢复,间隔时间为10秒,那么这就足够了:

// var slideTimer; // don't need this as you declare it below
var slideTimer = setInterval(nextSlide, 10000); // start slide show 10 secs


$(".next").click(function(){
    clearInterval(slideTimer);  // clear the interval
    slideTimer = setInterval(nextSlide, 10000);  // restart
});

function nextSlide() {
    $(".sliders img:first").appendTo(".sliders"); // only need to append in this - don't need to rebind
};

答案 1 :(得分:1)

我想你可能想做这样的事情:



// var slideTimer; // don't need this as you declare it below
var slideTimer = setInterval(nextSlide, 3000); // start slide show


$(".next").click(function(){
    clearInterval(slideTimer);  // clear the interval
    nextSlide();                // show the next slide
    slideTimer = setInterval(nextSlide, 3000); // start the interval again so next will show in 3 seconds - if this needs to start after 10 seconds, put it in a timeout of 7 seconds
});

function nextSlide() {
    $(".sliders img:first").appendTo(".sliders"); // only need to append in this - don't need to rebind
};




答案 2 :(得分:0)

var slideTimer;
var slideTimer = setInterval(nextSlide, 3000);


$(".next").click(function(){
    nextSlide();
});

function nextSlide() {
    $(".sliders img:first").appendTo(".sliders"); 
    $(".next").click(function(){
      clearInterval(slideTimer);
      slideTimer = setInterval(nextSlide, 3000);//add this to your code
    });
};