var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
// Timer with 1000ms (1 second) base interval resolution.
var timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.addTask({
name: 'job1', // unique name of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback: function (task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
var timer, intervalInSec = 2;
timer = setInterval(func, intervalInSec*1000, 30 ); // third parameter is argument to called function 'func'
function func(param){
console.log(param);
}
//您可以访问上面声明的 timer 的任何地方,调用clearInterval
$('.htmlelement').click( function(){ // any event you want
clearInterval(timer);// Stops or does the work
});
1831
setInterval() 返回一个间隔ID,您可以将其传递给 clearInterval() :
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
9 回答
上面的答案已经解释了setInterval如何返回句柄,以及如何使用此句柄取消Interval计时器 .
一些架构考虑:
请不要使用“无范围”变量 . 最安全的方法是使用DOM对象的属性 . 最简单的地方是“文件” . 如果通过启动/停止按钮启动刷新,您可以使用按钮本身:
由于函数是在按钮单击处理程序中定义的,因此您不必再次定义它 . 如果再次单击该按钮,则可以恢复计时器 .
你也可以通过添加一个事件监听器来停止间隔,让我们说一个ID为“stop-interval”的按钮:
HTML:
注意:间隔仍将执行,但不会发生任何事情 .
为什么不使用更简单的方法?添加课程!
只需添加一个告诉间隔不要做任何事情的类 . 例如:在悬停时 .
我一直在寻找这种快速简便的方法,所以我发布了几个版本,以尽可能多地介绍它 .
如果将
setInterval
的返回值设置为变量,则可以使用clearInterval
来停止它 .您可以设置一个新变量,并在每次运行时递增(递增一个),然后我使用条件语句来结束它:
我希望它有所帮助,这是对的 .
@cnu,
你可以停止间隔,当试试运行代码之前看看你的控制台浏览器(F12)...尝试注释clearInterval(触发器)再看一个控制台,而不是美化? :P
检查示例来源:
已经回答了......但是如果你需要一个特色的,可重复使用的计时器,它也支持不同时间间隔的多个任务,你可以使用我的TaskTimer(用于节点和浏览器) .
在您的情况下,当用户点击扰乱数据刷新时;如果需要重新启用,可以调用
timer.pause()
然后timer.resume()
.见more here .
声明变量以分配从setInterval(...)返回的值,并将分配的变量传递给clearInterval();
例如
//您可以访问上面声明的 timer 的任何地方,调用clearInterval
setInterval()
返回一个间隔ID,您可以将其传递给clearInterval()
:请参阅setInterval()和clearInterval()的文档 .