Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

328
Views
¿Cómo puedo mejorar el rendimiento setInterval por milisegundo usando ganchos en React?

Quiero crear un temporizador con milisegundos de 3 dígitos. (como un cronómetro) Entonces, uso setInterval con 1 milisegundo.

Por un tiempo, (alrededor de 20 segundos) fue muy lento. y hacer que mi computadora sea tan lenta. entonces debería actualizar esta página 😢

Lo uso con useEffect con setInterval. Creo que el problema es causado por volver a renderizar cada milisegundo. Pero no sé cómo mejorar el rendimiento.

Aquí está mi código (o code-sandbox https://codesandbox.io/s/peaceful-allen-gcdorn?file=/src/userTimer.js:0-603 )

 // App.js import { useState } from "react"; import useTimer from "./userTimer"; export default function App() { const [isStart, setIsStart] = useState(false); const [timer, setTimer] = useState("0.000"); useTimer(isStart, setTimer); return ( <div className="App"> <div style={{ fontSize: "4rem" }}>{timer}</div> </div> ); }
 // userTimer.js import { useEffect, useRef } from "react"; const useTimer = (isStart, setTimer) => { const refId = useRef(); useEffect(() => { if (isStart) { const startTime = Date.now(); const id = setInterval(function () { const elapsedTime = Date.now() - startTime; const formatTime = (elapsedTime / 1000).toFixed(3); setTimer(formatTime); }, 1); refId.current = id; } return () => clearInterval(refId.current); }, [isStart, setTimer]); const stopTimer = () => clearInterval(refId.current); return { stopTimer }; }; export default useTimer;

NOTA: Debo configurar setIsStart setTimer el componente principal (no en useTimer) porque quiero pasar ese gancho a otro componente secundario.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!