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

85
Vistas
High frequency counter in Reactjs

I need to write a program like this: the counter runs in the background counting from 0 to 100,000, then keeps going back to 0 and counting up... There is a button that will handle the event: on each button click the value of the counter at that time will be displayed on the screen. I planned to use setInterval but my program requires very high speed (count to 100000 in 1s). Does anyone have any solution?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you need something with that high a frequency, just look at the system time and the time you start counting at, á la

const counterPosition = ((+new Date() - startTime) * 100000) % 100000;

Here's an example - a frequency of 100,000 may prove difficult due to the inaccuracy of new Date()...

// TODO: this useRequestAnimationFrame implementation could be buggy;
//       it is here only to have CounterApp get updated "as fast as it can".
function useRequestAnimationFrame() {
  const [num, setNum] = React.useState(0);
  const keepUpdatingRef = React.useRef(true);
  React.useEffect(() => {
    const requestNext = () => {
      if(keepUpdatingRef.current) requestAnimationFrame(update);
    };
    const update = () => {
      setNum(n => n+1);
      requestNext();
    };
    requestNext();
    return () => keepUpdatingRef.current = false;
  }, []);
  return num;
}


function CounterApp({frequency}) {
  const frame = useRequestAnimationFrame();
  const [startTime] = React.useState(() => +new Date());
  const elapsed = (+new Date() - startTime) / 1000.0;
  const counter = Math.floor((elapsed * frequency) % frequency);
  return <div>{counter}</div>;
}

ReactDOM.render(<CounterApp frequency={100} />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></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