如何使 setInterval() 停止使用 clearInterval() 工作?

How to make a setInterval() stop using clearInterval() work?

好吧,我正在尝试制作一个 setInterval() 来停止使用 clearInterval(),这是代码:

let submitBPMkeeper = document.getElementById("submitBPMkeeper");

function startStopBPMkeeper(sr) {
  let bpmKeepTrack = document.getElementById("bpmSet");
  var test1 = 0;
  var t = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value);

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }
  if (sr == "start") {
    submitBPMkeeper.innerHTML = "Stop";
  } else if (sr == "stop") {
    submitBPMkeeper.innerHTML = "Start";
    clearInterval(t);
  }
}

submitBPMkeeper.addEventListener("click", function() {
  if (submitBPMkeeper.innerHTML == "Start") {
    startStopBPMkeeper("start");
  } else if (submitBPMkeeper.innerHTML == "Stop") {
    startStopBPMkeeper("stop");
  }
});
<div id="bpm">
  <h2>Tempo Keepper:</h2>
  <label for="bpmSet">BPM:</label>
  <input type="number" id="bpmSet" name="bpmSet" style="width:40px;" value="80">
  <button id="submitBPMkeeper">Start</button>
  <p id="baseInput"></p>
  <p id="testInput"></p>
</div>

如您所见,您无法阻止计数,我真的希望它在您按下停止时停止。

只需要在上层作用域定义区间变量即可。

const submitBPMkeeper = document.getElementById("submitBPMkeeper");
const bpmKeepTrack = document.getElementById("bpmSet");

let interval = null;

function toggleBPMKeeper() {
  let test1 = 0;

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }

  if (interval) {
    clearInterval(interval);
    interval = null;
    submitBPMkeeper.innerHTML = "Start";
  } else {
    interval = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value)
    submitBPMkeeper.innerHTML = "Stop";
  }
}

submitBPMkeeper.onclick = toggleBPMKeeper;

感谢 Teemu's 评论,我已经解决了我的问题:

let submitBPMkeeper = document.getElementById("submitBPMkeeper");
var t;

function startStopBPMkeeper(sr) {
  let bpmKeepTrack = document.getElementById("bpmSet");
  var test1 = 0;

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }
  if (sr == "start") {
    submitBPMkeeper.innerHTML = "Stop";
    t = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value);
  } else if (sr == "stop") {
    submitBPMkeeper.innerHTML = "Start";
    clearInterval(t);
  }
}

submitBPMkeeper.addEventListener("click", function() {
  if (submitBPMkeeper.innerHTML == "Start") {
    startStopBPMkeeper("start");
  } else if (submitBPMkeeper.innerHTML == "Stop") {
    startStopBPMkeeper("stop");
  }
});
<div id="bpm">
  <h2>Tempo Keepper:</h2>
  <label for="bpmSet">BPM:</label>
  <input type="number" id="bpmSet" name="bpmSet" style="width:40px;" value="80">
  <button id="submitBPMkeeper">Start</button>
  <p id="baseInput"></p>
  <p id="testInput"></p>
</div>

通过在我将按钮文本设置为“停止”的同一个 if 块中创建间隔,并将 t 声明拉到函数外部,我修复了它,使其可以正常工作。