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?


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