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

105
Visualizações
how to save a variable with the current data saved in an interval updating state

I am builidng a typicall stopwatch/clock app in here.

The issue: When clicking Pause Button then Split Button (which prints the elapsed time) and then start back, both the stopwatch and the printed time restart. That is because I am saving the Crono time in the handleClickSplit function. Any ideas on the best way to save that current paused time to prevent the bug?

This is the image

enter image description here

This is my code:

export default function Home({ enableCrono }) {
  const [cronoTime, setCronoTime] = useState({ h: 0, m: 0, s: 0, ms: 0 });
  const [printTime, setPrintTime] = useState([]);
  const [interv, setInterv] = useState();
  const [status, setStatus] = useState(0);
  // 0 => not running
  // 1 => start
  // 2 => pause
  // 3 => stop

  const start = () => {
    if (cronoTime.m === 60) {
      cronoTime.h++;
      cronoTime.m = 0;
    }
    if (cronoTime.s === 60) {
      cronoTime.m++;
      cronoTime.s = 0;
    }
    if (cronoTime.ms === 100) {
      cronoTime.s++;
      cronoTime.ms = 0;
    }
    cronoTime.ms++;
    return setCronoTime({
      ms: cronoTime.ms,
      s: cronoTime.s,
      m: cronoTime.m,
      h: cronoTime.h,
    });
  };

  const handleClickStart = () => {
    start();
    setStatus(1);
    setInterv(setInterval(start, 10));
  };
  const handleClickStop = () => {
    clearInterval(interv);
    setStatus(3);
  };
  const handleClickPause = () => {
    clearInterval(interv);
    setStatus(2);
  };

  const handleClickClear = () => {
    clearInterval(interv);
    setStatus(0);
    setCronoTime({ h: 0, m: 0, s: 0, ms: 0 });
    setPrintTime([]);
  };

  const handleClickSplit = () => {
    setPrintTime((prevtime) => [...prevtime, cronoTime]);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're saving in your printTime array a reference to the very same cronoTime object. Just save a new object, so that changes on cronoTime do not propagate to the object in printTime:

setPrintTime((prevtime) => [...prevtime, {...cronoTime}]);
about 4 years ago · Juan Pablo Isaza Relatório
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