在JavaScript中停止setInterval调用

我正在使用setInterval(fname, 10000); 在JavaScript中每10秒调用一次函数。 是否有可能停止在某些事件上调用它?

我希望用户能够停止重复刷新数据。

setInterval()返回一个间隔ID,您可以将其传递给clearInterval()

 var refreshIntervalId = setInterval(fname, 10000); /* later */ clearInterval(refreshIntervalId); 

请参阅setInterval()clearInterval()的文档。

如果将setInterval的返回值设置为variables,则可以使用clearInterval将其停止。

 var myTimer = setInterval(...); clearInterval(myTimer); 

你可以设置一个新的variables,并在每次运行时增加++(加1),然后使用条件语句来结束它:

 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如何返回句柄,以及如何使用这个句柄来取消间隔定时器。

一些架构考虑:

请不要使用“无范围”variables。 最安全的方法是使用DOM对象的属性。 最简单的地方将是“文件”。 如果刷新是通过开始/停止button启动的,则可以使用button本身:

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

由于该函数是在button点击处理程序中定义的,因此不必再次定义它。 如果再次点击该button,定时器可以恢复。

@cnu,

你可以停止间隔,当试运行代码之前查看你的控制台浏览器(F12)…尝试注释clearInterval(触发器)再次看看一个控制台,而不是美化? :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> 

已经回答了…但是如果你需要一个function强大的可重复使用的定时器,它也支持不同间隔的多个任务,你可以使用我的TaskTimer (Node和Browser)。

 // 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(); 

在你的情况下,当用户点击干扰数据刷新; 你可以调用timer.pause()然后timer.resume()如果他们需要重新启用。

在这里看到更多 。

声明variables以分配从setInterval(…)返回的值并将分配的variables传递给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); } 

//你上面定义的定时器的任何地方都调用clearInterval

 $('.htmlelement').click( function(){ // any event you want clearInterval(timer);// Stops or does the work }); 

为什么不使用更简单的方法? 添加一个class级!

只需添加一个告诉间隔不要做任何事情的类。 例如:在hover。

 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">&nbsp;</p> <button id="pauseInterval">Pause</button></p>