javascript - clearInterval() 不起作用,我不明白为什么

标签 javascript onclick cleartimeout

我正在尝试将 play/pause 按钮添加到一个计时器,该计时器具有根据 isRunning 的值决定要做什么的功能。第二次单击我的按钮而不是暂停时,计时器似乎添加了另一个 setTimeout,我不明白为什么。

var isRunning = false;

function start() {
  if(isRunning == false) {
    isRunning = true;
    setInterval(time, 1000);
    document.getElementById("play").className = "fa fa-pause";
  } 
  else if(isRunning == true) {
    isRunning = false;
    document.getElementById("play").className = "fa fa-play";
    console.log(isRunning);
    clearInterval(time);
  }
}

document.getElementById("play").onclick = start;

最佳答案

var isRunning = false;
var timeoutId; // Where the timeout id will be stored.

function start() {
  if(isRunning == false) {
    isRunning = true;
    timeoutId = setInterval(time, 1000);
    document.getElementById("play").className = "fa fa-pause";
  } 
  else if(isRunning == true) {
    isRunning = false;
    document.getElementById("play").className = "fa fa-play";
    console.log(isRunning);
    clearInterval(timeoutId); // clearInterval using timeout id saved before.
  }
}

document.getElementById("play").onclick = start;

欲了解更多信息,请访问 https://developer.mozilla.org/es/docs/Web/API/WindowTimers/setTimeout

关于javascript - clearInterval() 不起作用,我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502708/

相关文章:

javascript - 加载时可以单击按钮 #1,然后需要单击按钮 #2 两次。然后按钮 #1 也需要点击两次

jquery - 更改链接工具提示的类别

javascript - 定时器到期后重置setTimeout

javascript - 使用正交相机将鼠标点击转换为 3D 空间

javascript - 有没有办法知道 3 个(或更多)幻灯片中的哪一个处于事件状态?

javascript - 在 react-csv 中下载 CSV 后调用函数

javascript - 为什么 clearTimeout 在我的代码中不起作用? javascript

javascript - Cloudinary上传小部件-样式化上传预览图像(宽度和高度)

javascript - 我应该如何从js中的多个跨度中获取 'This is my name '?

javascript - 如何停止或暂停该程序?