我必须在下一个 requestAnimationFrame 之前取消 AnimationFrame 吗?

Do I have to cancelAnimationFrame before next requestAnimationFrame?

这里我有一个简单的 React 计时器应用程序。在 animate 方法中调用下一个 requestAnimationFrame 之前,我是否需要始终调用 cancelAnimationFrame

我从某处读到,如果我在单个回调中调用多个 requestAnimationFrame,则需要 cancelAnimationFrame。但在我的示例中,我在单个回调中调用单个 requestAnimationFrame

在这篇文章中,当一个人说不需要而另一个人说需要时,我什至感到困惑:https://medium.com/@moonformeli/hi-caprice-liu-8803cd542aaa

function App() {
  const [timer, setTimer] = React.useState(0);
  const [isActive, setIsActive] = React.useState(false);
  const [isPaused, setIsPaused] = React.useState(false);
  const increment = React.useRef(null);
  const start = React.useRef(null);

  const handleStart = () => {
    setIsActive(true);
    setIsPaused(true);
    setTimer(timer);
    start.current = Date.now() - timer;
    increment.current = requestAnimationFrame(animate);
  };

  const animate = () => {
    setTimer(Date.now() - start.current);
    cancelAnimationFrame(increment.current);
    increment.current = requestAnimationFrame(animate);
  };

  const handlePause = () => {
    cancelAnimationFrame(increment.current);
    start.current = 0;
    setIsPaused(false);
  };

  const handleResume = () => {
    setIsPaused(true);
    start.current = Date.now() - timer;

    increment.current = requestAnimationFrame(animate);
  };

  const handleReset = () => {
    cancelAnimationFrame(increment.current);
    setIsActive(false);
    setIsPaused(false);
    setTimer(0);
    start.current = 0;
  };

  return (
    <div className="app">
      <div className="stopwatch-card">
        <p>{timer}</p>
        <div className="buttons">
          {!isActive && !isPaused ? (
            <button onClick={handleStart}>Start</button>
          ) : isPaused ? (
            <button onClick={handlePause}>Pause</button>
          ) : (
            <button onClick={handleResume}>Resume</button>
          )}
          <button onClick={handleReset} disabled={!isActive}>
            Reset
          </button>
        </div>
      </div>
    </div>
  );
};
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

不,你不需要在递归函数中取消raf,因为raf就像一个setTimeout,但是它执行函数与屏幕刷新率完美同步,所以它只执行一次:

const animate = ()=>{
    setTimer(Date.now()-start.current)
    increment.current = requestAnimationFrame(animate)
  }