Reactjs中的高频计数器

High frequency counter in Reactjs

我需要写一个这样的程序:计数器在后台运行,从 0 计数到 100,000,然后一直回到 0 并向上计数...有一个按钮可以处理事件:在每个按钮点击时计数器的值会显示在屏幕上。我计划使用 setInterval 但我的程序需要非常高的速度(1 秒内数到 100000)。有人有解决办法吗?

如果你需要这么高频率的东西,只要看看系统时间和你开始计数的时间,ála

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

这是一个例子 - 由于 new Date()...

的不准确性,100,000 的频率可能会被证明是困难的

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