我无法停止setInterval

时间:2018-05-24 05:29:23

标签: javascript setinterval clearinterval

我有两个buttons。一个onClick运行一个使用var intId = setInterval{function(), 30}的函数 在第二个button我尝试使用clearInterval(intId)停止setInterval,但intId不是全局可行的,如果我将整个setInterval放在按钮功能之外,它就无法运行。

  

运行按钮

var intID == 0;

function runButton() {
  var c = document.getElementById("can1");
  var ctx = c.getContext("2d");

  var speed = 2;
  var posX = 20;
  var posY = 20;

  var intID = setInterval(function() {
    posX += speed;
    ctx.clearRect(0, 0, c.width, c.height);

    ctx.fillStyle = "black";
    ctx.fillRect(posX, posY, 20, 20);

    if (intID == 1) {
        clearInterval(intID);
        }
  }
      , 30);

}
  

停止按钮

function stopButton() {
  var c = document.getElementById("can1");
  var ctx = c.getContext("2d");


  clearInterval(intID);
  intID == 1;

  ctx.clearRect(0, 0, c.width, c.height);
  c.style.backgroundColor = red;
}

1 个答案:

答案 0 :(得分:0)

请尝试以下操作。

var intervalID = 1;

function runButton() {
  var c = document.getElementById("can1");
  var ctx = c.getContext("2d");

  var speed = 2;
  var posX = 20;
  var posY = 20;

  var intID = setInterval(function() {
    posX += speed; //variable 'x' had to change to 'posX'
    ctx.clearRect(0, 0, c.width, c.height);

    ctx.fillStyle = "black";
    ctx.fillRect(posX, posY, 20, 20);

    if(intervalID == 0) {
        clearInterval(intID);
    }
  }, 30);
}

function stopButton() {
  var c = document.getElementById("can1");
  var ctx = c.getContext("2d");

  intervalID = 0;

  ctx.clearRect(0, 0, c.width, c.height);
  c.style.backgroundColor = red;
}