简体   繁体   English

setInterval,clearInterval无法正常工作

[英]setInterval, clearInterval not working

I have a requirement where I need to call a function repeatedly which calls setInterval. 我有一个需要重复调​​用setInterval的函数的要求。 The problem I encountered is, if a function is generated(say every 1second) and it is set using setInterval; 我遇到的问题是,如果生成一个函数(例如每隔1秒),并且使用setInterval进行设置; if we call setInterval twice/more without a clearInterval in between the function keeps on calling itself. 如果我们两次或更多次调用setInterval,而在两次调用之间没有clearInterval,则函数将继续调用自身。 Ex : 例如:

<!DOCTYPE html>
 <html>
 <body>

  <p>A script on this page starts this clock:</p>

   <p id="demo"></p>
   <button onclick="myStartFunction()">Start time</button>
   <button onclick="myStopFunction()">Stop time</button>

<script>

var myVar;
function myStartFunction(){
  myVar = setInterval(function(){ myTimer() }, 1000);
 }

function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
  console.log(myVar);
  clearInterval(myVar);
  console.log(myVar);
}
 </script>

 </body>
 </html>

If I click the Start Time button twice without clicking Stop time in between, the function doesn't stop. 如果我两次单击“开始时间”按钮而没有在其间单击“停止时间”,则该功能不会停止。 This is just an example of the scenario. 这只是该场景的一个示例。 Anyway to resolve this? 无论如何要解决这个问题?

In your startFunction, just clear any existing intervals. 在startFunction中,只需清除所有现有间隔。 Otherwise you are creating multiple intervals, but only storing a reference to the last interval created. 否则,您将创建多个间隔,但仅存储对最后创建的间隔的引用。

For example: 例如:

function myStartFunction(){
  if(myVar) {
    myStopFunction();
  }
  myVar = setInterval(function(){ myTimer() }, 1000);
 }

You are overwriting the same myVar over and over again ... That means the stop function will only stop the last timer started. 您将一遍又一遍地覆盖同一个myVar。这意味着停止功能将仅停止上一次启动的计时器。 If you only want at most one setInteval to run, just add a call to the stop function before starting. 如果只希望最多运行一个setInteval,则只需在启动前将调用添加到stop函数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM