停止JavaScript中的setInterval调用

  • Post author:
  • Post category:java


我正在使用


setInterval

(fname, 10000);



JavaScript

中每10秒调用一次函数。 是否可以在某个事件中停止调用它?

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


#1楼


setInterval()

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

clearInterval()

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

有关


setInterval()





clearInterval()


请参阅文档。


#2楼

如果将

setInterval

的返回值设置为变量,则可以使用

clearInterval

停止它。

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

#3楼

上面的答案已经解释了setInterval如何返回一个句柄,以及如何使用该句柄取消Interval计时器。

一些架构上的考虑:

请不要使用“无作用域”变量。 最安全的方法是使用DOM对象的属性。 最简单的地方是“文档”。 如果刷新是通过“开始/停止”按钮启动的,则可以使用该按钮本身:

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

由于该函数是在按钮单击处理程序内部定义的,因此您无需再次定义它。 如果再次单击该按钮,则计时器可以恢复。


#4楼

您可以设置一个新变量,并在每次运行时使它递增++(加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);
});

我希望它会有所帮助,这是正确的。


#5楼

为什么不使用更简单的方法? 添加课程!

只需添加一个告诉间隔什么都不做的类。 例如:悬停。

 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> 

我一直在寻找这种快速,简便的方法,因此,我发布了多个版本,以尽可能多地向人们介绍该方法。


#6楼

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


#7楼

已经回答…但是,如果您需要一个功能强大且可重复使用的计时器,该计时器还支持不同时间间隔的多个任务,则可以使用我的

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

如果他们需要重新启用。


在这里

查看

更多


#8楼

声明变量以分配从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);
}

//您可以访问在调用clearInterval之前声明的

计时器的

任何地方

$('.htmlelement').click( function(){  // any event you want

       clearInterval(timer);// Stops or does the work
});

#9楼

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>

注意:该间隔仍将执行,但是什么也不会发生。


#10楼

clearInterval()方法可用于清除使用setInterval()方法设置的计时器。

setInterval始终返回ID值。 可以在clearInterval()中传递此值以停止计时器。 这是一个计时器的示例,该计时器从30开始并在其变为0时停止。

  let time = 30;
  const timeValue = setInterval((interval) => {
  time = this.time - 1;
  if (time <= 0) {
    clearInterval(timeValue);
  }
}, 1000);

#11楼

这就是我使用clearInterval()方法在10秒后停止计时器的方式。

 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> 


#12楼

使用setTimeOut在一段时间后停止间隔。

var interVal = setInterval(function(){console.log("Running")  }, 1000);
 setTimeout(function (argument) {
    clearInterval(interVal);
 },10000);