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

124
Visualizações
React.js, implementing timer, getting weird behaviour

I am trying to create a simple timer with React, where start button starts the timer, and stop button pauses it. However this gives some unexpected behavior.

First click on start, the timer changes to 1 and pauses, on second click it oscillates between 1 and 2. Unable to understand why this is happening. Any help would be greatly appreciated!

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [time, setTime] = useState(0)
  let t;
  function startTime(){
    t = setInterval(()=>{
      setTime(time+1);
    },1000)
  }
  function stopTime(){
    clearInterval(t);
  }
  return (
    <div className="App">
      <h1>{time}</h1>
      <button onClick={startTime}>Start</button>
      <button onClick={stopTime}>Stop</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As you did, on first click you create a function in memory that will call setTime(0+1) for ever, as 0 is the value of time when you registered that function in memory. To have the updated time, you would wanna pass a function to setTime.

Also, to memoize the interval reference, you should be using a React ref, as a normal variable will come to its initial value at each render. Here is a working example on CodeSandbox and the code below:

import { useState, useRef } from "react";
import "./styles.css";

export default function App() {
  const [time, setTime] = useState(0)
  const timerRef = useRef();
  function startTime(){
    timerRef.current = setInterval(()=>{
      setTime(time =>time+1);
    },1000)
  }
  function stopTime(){
    clearInterval(timerRef.current);
  }

  return (
    <div className="App">
      <h1>{time}</h1>
      <button onClick={startTime}>Start</button>
      <button onClick={stopTime}>Stop</button>
    </div>
  );
}
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