-2

I want my timer to stop and reload to 0 when it hits 25 with a clearInterval but it says that the variable refreshInterval is undefined. The timer resets but it keeps on going and I want it completely to stop until its enabled again.

function removeMe() {
  var refreshInterval = setInterval(setTime, 1000);
  display.removeBen();
  totalSeconds = 0;
};

//timer1//
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;

function setTime() {
  if (totalSeconds == 1) {
    game.clickValue + 2;
  }
  if (totalSeconds == 25) {
    game.clickValue - 2;
    clearInterval(refreshInterval);
    totalSeconds = 0;
  } else
    ++totalSeconds;
  secondsLabel.innerHTML = pad(totalSeconds % 60);
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}

function pad(val) {
  var valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
  }
}
//timer1//
VLAZ
  • 26,331
  • 9
  • 49
  • 67
umbreonben
  • 33
  • 4
  • 2
    That's true. `refreshInterval` is only declared inside `removeMe`. If you want it to be accessible to `setTime` you have to declare it in an environment that's accessible to both `removeMe` and `setTime`. – Felix Kling Jan 29 '21 at 09:10
  • How can I do this? – umbreonben Jan 29 '21 at 09:12
  • Put `var refreshInterval;` above `function removeMe() {` and change `var refreshInterval = setInterval(...)` to `refreshInterval = setInterval(...)`. – Felix Kling Jan 29 '21 at 09:13
  • 1
    I'd suggest you read up on [variable scopes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) – Liam Jan 29 '21 at 09:14
  • 1
    [What is the scope of variables in JavaScript?](https://stackoverflow.com/q/500431) – VLAZ Jan 29 '21 at 09:23

1 Answers1

0

Move refreshInterval up to the global scope so that is accessible from within both the removeMe and setTime function scopes.

let refreshInterval;

function removeMe() {
  refreshInterval = setInterval(setTime, 1000);
};

//timer1//
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;

function setTime() {
  if (totalSeconds == 25) {
    clearInterval(refreshInterval);
    totalSeconds = 0;
  } else
    ++totalSeconds;
  secondsLabel.innerHTML = pad(totalSeconds % 60);
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}

function pad(val) {
  var valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
  }
}


removeMe()
<p id="minutes"></p>
<p id="seconds"></p>
ksav
  • 20,015
  • 6
  • 46
  • 66