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

84
Views
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 answers
Answer question

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