如何在清除后自动重新启动间隔?

How to restart an interval automatically after cleared it?

我正在创建幻灯片,当我加载页面时它会自动 运行,如果有人按下 prev/next 按钮 (clearInterval),它就会停止。我的问题是我希望间隔在一段时间后并在它被清除后重新启动。我试过 setTimeout,但我认为我做错了什么。

滑块基于 "ul",里面有图像,它将通过更改列表的边距来显示每个图像。 这些按钮位于列表的两侧,带有 "data-mov" 属性,它将 return "prev" 或 "next" 将该值保存在名为 "dir" 的变量中。

我留下了我拥有的实际 js 代码,我认为关键点在 "slide" 函数内。

在此先感谢您!

( function(){

var slider = $( '.slider' );

var slides = slider.find("li").length;

var actual = 0;

var width = 310;

var interval = setInterval( function(){
    slide( 'next' );
}, 1500 );


function slide( dir, click ){

    if ( click ){
       clearInterval( interval );
    }

    ( dir === "next" ) ? actual -- : actual ++;
    if ( actual > 0 ) {
        actual = ( slides - 1 ) *  -1;
    }else if ( actual <= ( slides * -1  ) ) {
        actual = 0;
    }
    var margin = actual * width;

    slider.animate({
        marginLeft: margin
    }, 450);

}

$('.btn-slide').on('click', function () {

    var dir = $(this).data("mov");
//when the button is pressed we send "true" for the "click" argument
    slide( dir , true);
});

})();

在我看来,使用 setTimout 是重新开始幻灯片放映的完全有效的方法。

您可以通过这样做轻松实现您的目标:

     var restartTimer;
     function slide( dir, click ){
        if ( click ){
           clearInterval( interval );
           clearTimeout(restartTimer);

           restartTimer = setTimeout(function () {
               setInterval(slide, 1500, 'next');
           }, 10000); // insert time after which you want it to continue here  
        }

        ( dir === "next" ) ? actual -- : actual ++;
        if ( actual > 0 ) {
            actual = ( slides - 1 ) *  -1;
        }else if ( actual <= ( slides * -1  ) ) {
            actual = 0;
        }
        var margin = actual * width;

        slider.animate({
            marginLeft: margin
        }, 450);
    }

setTimout 将在(在本例中)10000 毫秒后重新启动它,除非您碰巧手动移动滑块,否则超时将由 clearTimeout 函数重置。它会从那一点开始等待,直到 10000 毫秒过去,之后它会再次继续。