我正在使用setInterval(fname, 10000);
在JavaScript中每10秒调用一个函数。有没有可能在某个事件中停止调用它?
我想让用户能够停止重复刷新数据。
setInterval()
返回一个区间ID,你可以把它传递给clearInterval()
。
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
参见setInterval()
和clearInterval()
的文档。
如果你把setInterval
的返回值设置为一个变量,你可以用clearInterval
来停止它。
var myTimer = setInterval(...);
clearInterval(myTimer);
你可以设置一个新的变量,并在每次运行时让它以++(数一数)递增,然后我用一个条件语句来结束它。
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
我希望这有帮助,而且是正确的。
上面的答案已经解释了setInterval如何返回一个句柄,以及这个句柄是如何用来取消Interval定时器的。
一些架构上的考虑。
请不要使用"scope-less" 变量。 最安全的方法是使用DOM对象的属性。 最简单的地方是"document"。 如果刷新是由一个开始/停止按钮启动的,你可以使用按钮本身。
<a onclick="start(this);">Start</a>
<script>
function start(d){
if (d.interval){
clearInterval(d.interval);
d.innerHTML='Start';
} else {
d.interval=setInterval(function(){
//refresh here
},10000);
d.innerHTML='Stop';
}
}
</script>
由于该函数是在按钮点击处理程序中定义的,所以你不必再次定义它。 如果按钮再次被点击,定时器可以恢复。
已经回答过了... 但如果你需要一个有特色的、可重复使用的定时器,同时支持不同时间间隔的多个任务,你可以使用我的TaskTimer(适用于Node和浏览器)。
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
在你的案例中,当用户点击打扰数据刷新时,你也可以调用timer.pause()
然后timer.resume()
如果他们需要重新启用。
你也可以调用timer.pause()
然后timer.resume()
如果他们需要重新启用。
参见【更多内容】[2]。
1:
@CNU。
你可以停止间隔,当尝试运行代码前看你的控制台浏览器(F12)...。 试着注释clearInterval(trigger)又是一个控制台,而不是美化器? :P
检查一个源例。
var trigger = setInterval(function() {
if (document.getElementById('sandroalvares') != null) {
document.write('<div id="sandroalvares" style="background: yellow; width:200px;">SandroAlvares</div>');
clearInterval(trigger);
console.log('Success');
} else {
console.log('Trigger!!');
}
}, 1000);
<div id="sandroalvares" style="background: gold; width:200px;">Author</div>
<!--结束片段-->
clearInterval()方法可用于清除与settail()方法一起设置的定时器。
setInterval总是返回一个ID值。 这个值可以通过clearInterval()方法来停止定时器。 下面是一个定时器的例子,它从30开始计时,当它变成0时停止。
let time = 30;
const timeValue = setInterval((interval) => {
time = this.time - 1;
if (time <= 0) {
clearInterval(timeValue);
}
}, 1000);
声明变量,将setInterval(...)返回的值分配给这个变量。 并将分配的变量传递给clearInterval()。
例如:
var timer, intervalInSec = 2;
timer = setInterval(func, intervalInSec*1000, 30 ); // third parameter is argument to called function 'func'
function func(param){
console.log(param);
}
}
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
});
var keepGoing = true;
setInterval(function () {
if (keepGoing) {
//DO YOUR STUFF HERE
console.log(i);
}
//YOU CAN CHANGE 'keepGoing' HERE
}, 500);
你也可以通过添加一个事件监听器来停止间隔,比如说一个ID为"stop-interval"的按钮。
$('buuton#stop-interval').click(function(){
keepGoing = false;
});
HTML。
<button id="stop-interval">Stop Interval</button>
注意:"间歇期 "仍然会被执行,但不会发生任何事情。 间隔仍然会被执行,但什么也不会发生。
我是这样使用clearInterval()方法在10秒后停止定时器的。
<!--开始片段。 js hide: false console: true babel.false -->-- begin snippet: js hide: false console: true false -->
function startCountDown() {
var countdownNumberEl = document.getElementById('countdown-number');
var countdown = 10;
const interval = setInterval(() => {
countdown = --countdown <= 0 ? 10 : countdown;
countdownNumberEl.textContent = countdown;
if (countdown == 1) {
clearInterval(interval);
}
}, 1000)
}
<head>
<body>
<button id="countdown-number" onclick="startCountDown();">Show Time </button>
</body>
</head>
<!--结束片段-->
只需添加一个告诉区间不做任何事情的类。 比如说 on hover: <!
<!--开始snippet。 js hide: false -->
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');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- 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>
<!--结束片段-->。
我'一直在寻找这种快速简单的方法,所以我'发布几个版本,尽可能多的人介绍它。