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

92
Visualizações
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 Respostas
Responde à pergunta

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 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