0

so im trying to make a speaker timer, but i want the reset it using another function so that i can have a "Start" & "Stop" buttons for timer. Timer works like this;

function startspeaker() {
  if (j == 0) {
    j = 1;
    var elemj = document.getElementById("speakerbar");
    var widthj = 1;
    var idj = setInterval(frame, speakerDureation.value);
    function frame() {
      if (widthj >= 100) {
        clearInterval(idj);
        j = 0;
      } else {
        widthj++;
        elemj.style.width = widthj + "%";
      }
    }
  }
}

JavaScript is adjusting the width of progress bar. I tried the code below but it didn't work. Need some help here. Thx anyway.

function resetTimer() {
  var elemj = document.getElementById("speakerbar");
  elemj.style.width = "100%";
  clearInterval(idj);
}

1 Answers1

1

idj variable inside startspeaker() is defined in local scope - the variable will not exist after function is done executing. To fix this you need to declare idj variable outside of the function:

var idj;

function startspeaker() {
    ...
    idj = setInterval(...)
}

function resetTimer() {
    // now you can use idj here
}

or

function startspeaker() {
    ...
    var idj = setInterval(...)
    ...
    return idj;
}

var idj = startspeaker();

function resetTimer() {
    // now you can use idj here
}
Samuel Olekšák
  • 389
  • 4
  • 12