Home > Back-end >  Do I have to cancelAnimationFrame before next requestAnimationFrame?
Do I have to cancelAnimationFrame before next requestAnimationFrame?

Time:04-26

Here I have a simple timer application in React. Do I need to always call cancelAnimationFrame before calling next requestAnimationFrame in animate method?

I read from somewhere that if I call multiple requestAnimationFrame within single callback, then cancelAnimationFrame is required. But in my example, I am calling single requestAnimationFrame in a single callback.

I got even confused when one said no need while another one said need in this article: 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>

CodePudding user response:

No you don't need to cancel the raf in the recursive function, since a raf is just like a setTimeout, but it executes the function in perfect sync with the screen refresh rate, so it executes only once:

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