-1

I have two buttons. The one onClick runs a function that uses a var intId = setInterval{function(), 30} On the second button i try to stop the setInterval with clearInterval(intId) but intId is not global virable and if i put the whole setInterval outside of the function of the button it can't run.

run button

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

}

stop button

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;
}
Nick Tsigkros
  • 7
  • 1
  • 1
  • 4

1 Answers1

0

Try as follows.

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;
}
Nick Tsigkros
  • 7
  • 1
  • 1
  • 4
Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28
  • I see the logic of placing a new global `var intervalID` but it doesn't work either and i can't understand why. [code here](https://codepen.io/TsigkrosNikos/pen/LmojNV) – Nick Tsigkros May 24 '18 at 06:22
  • @NickTsigkros, I have got two errors in pen. `x` is not defined and `red` is not defined. Please declare x and put red in quotes. – Harish Kommuri May 24 '18 at 06:29
  • Yes i just found the same thing because i copied the whole code from here! Now it works perfect now thank you!!! – Nick Tsigkros May 24 '18 at 06:33