1

I am trying to create a one-minute timer that runs twice. During the first run, the timer will countdown to 0. Then, the timer will reset to one minute and start the countdown again. To create this timer, I am using Javascript, which is a programming language that I am not particularly skilled at.

The timer works when I use it just once. However, when I try to use it in a for loop, create a recursive function, or even run it twice in a row by calling the function twice, the countdown is not consecutive. For example, it will display 4, then 2, then -1, even though the countdown is supposed to be consecutive and end at 0.

I have searched on StackExchange to find similar questions. I followed the answer to this question, but the countdown displayed NaN instead of the proper numbers. I have also read through a number of other questions, but their answers have not worked for me.

My Javascript code is:

            window.onload = function() {
                var seconds = 60;
                function timeout() {
                    setTimeout(function () {
                        seconds--;
                        document.getElementById("time").innerHTML = String(seconds)
                        if (seconds > 0){
                            timeout();
                        }
                    }, 1000);
                }
                timeout()
                seconds = 60;
                timeout()
            };

document.getElementById("time") refers to an empty paragraph with time as its ID.

Thank you in advance.

SuperNovaCoder
  • 155
  • 1
  • 7

1 Answers1

1

Your code is running the function twice at the same time. Try this, setting a separate counter, and stopping the timer once the count has reached a set number:

window.onload = function() {
  var seconds = 60;
  var count = 1;

  function timeout() {
    setTimeout(function() {
      seconds--;
      document.getElementById("time").innerHTML = String(seconds)
      if (seconds > 0) {
        timeout();
      } else {
        seconds = 60;
        count++;
        if (count <= 2) {
          timeout();
        }
      }
    }, 1000);
  }
  timeout();
};
<p id="time"> </p>
sideroxylon
  • 4,338
  • 1
  • 22
  • 40