【问题标题】:clearInterval(); not working清除间隔();不工作
【发布时间】:2013-04-14 02:39:59
【问题描述】:

我正在制作一个图像滚动器,它每隔几秒(为了调试为 10 秒)或当用户单击图像时自动推进图像。我的代码(如下所示)有效,但如果图像的手动(单击)推进完成,我想“重置”10 秒计数器。我怎样才能做到这一点?我似乎对 clearInterval 没有运气。

... 
setInterval('gallery()',10000);
$("#gallery").click(function() {
clearInverval();// <--- not working
gallery();
});
…

我看到其他人将变量定义为(在我的情况下)setInterval('gallery()',10000);,但我也无法让它工作 =/

PS 我对 C 以外的语言了解有限

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    setInterval 方法返回间隔句柄,您可以使用它来停止它:

    var handle = window.setInterval(gallery,10000);
    $("#gallery").click(function() {
      window.clearInterval(handle);
      gallery();
    });
    

    【讨论】:

      【解决方案2】:

      也许你可以这样做:

      var handle = setInterval(gallery,10000);
      $("#gallery").click(function() {
          clearInterval(handle);
      
          /*
           * your #gallery.click event-handler code here
           */
      
          //finally, set automatic scrolling again
          handle = setInterval(gallery,10000);
      });
      

      【讨论】:

        【解决方案3】:

        您需要将 setInterval 设置为变量才能使其工作..

        var interval = setInterval(gallery, 10000);
        $('#gallery').click(function() {
            clearInterval(interval);
        });
        

        【讨论】:

        • 这样做完全破坏了我的点击处理程序 =/
        【解决方案4】:

        在进行基于原型的编码时,我努力制作一个简单的暂停/继续处理程序,因此不想使用任何外部插件。

        下面的代码非常不言自明,有望节省其他编码人员的时间。

        非功能示例:

            /** THIS DID NOT WORK 
            function Agent( name )
            {
                 this.name = name;
                 this.intervalID = undefined; // THIS DID NOT WORK!!!
            } // constructor
        
            Agent.prototype.start = function( speed )
            {
                var self = this;
                this.intervalID = setInterval( function(){ self.act(); }, speed );
            }; // start
        
            Agent.prototype.pause = function()
            {
                clearInterval( this.intervalID );
                console.log( "pause" );
            }; // pause
            **/
        

        您必须这样做:

        var intervalID = undefined;
        function Agent( name )
        {
             this.name = name;
        } // constructor
        
        Agent.prototype.start = function( speed )
        {
            var self = this;
            intervalID = setInterval( function(){ self.act(); }, speed );
        }; // start
        
        Agent.prototype.pause = function()
        {
            clearInterval( intervalID );
            console.log( "pause" );
        }; // pause
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多