Countdown does not stop at Zero

Asked

Viewed 145 times

-3

Countdown timer doesn’t stop when it reaches "0". I need the timer to stop when it reaches "0" and when clicking on the "start" button it starts with the set value, which is "1 min" and decreases to "0" again. Stop and Add Buttons 1 min are working.

Below follows codes of buttons:

    this.iniciarCronometro = this.iniciarCronometro.bind(this);
    this.pararCronometro = this.pararCronometro.bind(this);
    this.tempoFormatado = this.tempoFormatado.bind(this);
    this.somarUmSegundo = this.somarUmSegundo.bind(this);
    this.state = {
      contadorSegundo: 0,
      contadorMinuto: 1,
    };
  }

  iniciarCronometro() {
    var intervalId = setInterval(this.somarUmSegundo, 100);
    this.setState({
      intervalId: intervalId,
    });
  }

  pararCronometro() {
    clearInterval(this.state.intervalId);
    this.setState({
      contadorSegundo: 0,
      contadorMinuto: 1,
    });
  }

  somarUmMinuto() {
    this.setState({
      contadorMinuto: this.state.contadorMinuto + 1,
    });
  }

The Code below makes the chronometer work. The way it is implemented the counter does not stop when it reaches "0". I need it to stop when I reset and when I call the start function it starts from the set value " 1".

somarUmSegundo() {
    let segundos = this.state.contadorSegundo;
    let minutos = this.state.contadorMinuto;

    minutos == 1 || segundos > 0;
    if (segundos == 0) {
      segundos = 59;
      minutos = minutos - 1;
    } else {
      segundos = segundos - 1;
    }

    this.setState({
      contadorSegundo: segundos,
      contadorMinuto: minutos,
    });
  }
  • 1

    Your question is not very clear, have to point out more details?

  • @Francisco updated the code and put more information.

  • Dude, now you have too much information kk. If possible structure the question following the model of [mcve].

  • @Francisco updated.

1 answer

1


Its function somarUmSegundo() doesn’t make much sense. Try this way:

somarUmSegundo() {
    if (this.state.contadorSegundo == 0) {
        if (this.state.contadorMinuto > 0) {
            this.setState(antigo => ({
                contadorMinuto: antigo.contadorMinuto - 1
                contadorSegundo: 59
            }));
        }
        else {
            clearInterval(this.state.intervalId);
            return;
        }
    }

    this.setState(antigo => ({
        contadorSegundo: antigo.contadorSegundo - 1
    }));
}
  • The Code worked perfectly. But when the count ends the value already returns to "01:00 min" automatically. I need it to be reset, only after clicking the start button it starts decreasing from "01:00 min". I tried to modify your code here but I’m having trouble.

  • I edited the answer, try to agr @Philipe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.