Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
How do I manage intervals with event handlers in React JS?

I am learning React JS and I started building a Pomodoro clock. I do not understand how to start a specified interval upon clicking a button and stopping the timer upon clicking a separate button. When I click "play" the timer stalls at 24:059. When I click the same button, it goes to 24:058 and jumps back to 24:059 then repeats. When I click it again, it goes to 24:057, etc.

When I remove the switch(seconds) condition in decreaseTimer() and simply insert setSeconds((seconds) => seconds - 1); the seconds decrement by 1 as expected. How do I fix this issue? I appreciate all the help and advice here. Thank you!

PomoTimer.js

import { useEffect, useState } from "react";

const PomoTimer = (props) => {
  const [seconds, setSeconds] = useState(0);
  const [intervalId, setIntervalId] = useState("");
  const [isSession, setSession] = useState(true);

  const startTimer = () => {
    let newIntervalId = setInterval(decreaseTimer, 1000);

    setIntervalId((intervalId) => newIntervalId);
  };

  const stopTimer = () => {
    clearInterval(intervalId);
  };

  const decreaseTimer = () => {
    switch (seconds) {
      case 0:
        props.onTimerMinuteChange(props.timerMinute - 1);
        setSeconds((seconds) => 59);
        break;
      default:
        setSeconds((seconds) => seconds - 1);
        break;
    }
  };

  const resetTimer = () => {
    clearInterval(intervalId);

    props.resetTimer();
    props.onPlayChange(false);

    setSeconds(0);
  };

  return (
    <section>
      <section>
        {/* <h4>{session === true ? "Session" : "Break"}</h4> */}
        <span>{props.timerMinute}</span>
        <span>:</span>
        <span>{seconds === 0 ? "00" : "0" + seconds}</span>
      </section>
      <section>
        <button onClick={startTimer}>Play</button>
        <button onClick={stopTimer}>Stop</button>
        <button onClick={resetTimer}>Refresh</button>
      </section>
    </section>
  );
};

export default PomoTimer;
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda