clearInterval(); 不工作

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

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

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

PS我对C以外的语言知识有限

setInterval方法返回间隔的句柄,用于停止它:

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

也许你可以这样做:

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

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

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

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

下面的代码非常明确,希望能节省其他编码人员的时间。

非function性示例:

  /** 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