Search code examples
javascripttypescripttimersetintervalseconds

Counter keeps resetting to declared variable on setInterval loop


I am trying to show a timer that rises each second using setInterval.

The variable seems to reset itself on each loop though; the result being that the display on the HTML page doesn't change.

I've moved the variables outside of the function, but this doesn't work. Not really sure where to go from here.

    this.intervalFour = setInterval(() => this.totalTime(this.secs, this.restSecs), 1000);


    totalTime(seconds, rests) {
        var fullTime = seconds * 8 + rests * 7;
        fullTime--;
        var secCounter: any = 0;
        var minCounter: any = 0;
        secCounter++;
        if (secCounter < 10) {
            secCounter = "0" + secCounter;
        }
        if (minCounter < 10) {
            minCounter = "0" + minCounter;
        }
        if (secCounter == 60) {
            secCounter = 0;
            minCounter++;
        }
        if (fullTime = 0) {
            clearInterval(this.intervalFour);
        }
        this.m.innerHTML = minCounter;
        this.s.innerHTML = secCounter;
        console.log(secCounter, minCounter, "test");
}

I know this is a silly thing to get stuck on, but I can't find the solution to get the secCounter to rise by one on each loop.


Solution

  • You can try the following approach.

    Though I don't have certain value therefore I commented that code, you can uncomment that code as per your need:

    <script type="text/javascript">
          var secs = 10;
          var restSecs = 10;
          var secCounter = 0;
          var minCounter = 0;
          this.intervalFour = setInterval(() => this.totalTime(this.secs, this.restSecs), 1000);
    
    
        function totalTime(seconds, rests) {
            var fullTime = seconds * 8 + rests * 7;
            fullTime--;
            this.secCounter++;
            if (this.secCounter < 10) {
                this.secCounter = "0" + this.secCounter;
            }
            if (this.minCounter < 10) {
                this.minCounter = "0" + this.minCounter;
            }
            if (this.secCounter == 60) {
                this.secCounter = 0;
                this.minCounter++;
            }
            // if (fullTime = 0) {
            //     clearInterval(this.intervalFour);
            // }
            console.log("this.minCounter" , this.minCounter);
            console.log("this.secCounter" , this.secCounter);
            // this.m.innerHTML = this.minCounter;
            // this.s.innerHTML = this.secCounter;
            console.log(this.secCounter, this.minCounter, "test");
    }
    

    In this solution, the seconds gets perfectly increasing on every second.