Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda