import { useEffect } from 'react';

let isRunning = false;
const callbacks: (() => void)[] = [];

// let now = Date.now();
const run = () => {
  // let runTime = Date.now();
  // if (runTime - now > 20) {
  //   console.log(runTime - now);
  // }
  // now = runTime;
  requestAnimationFrame(run);
  isRunning = true;
  callbacks.forEach((c) => c());
};

const useAnimationFrame = (callback: () => void, shouldRun: boolean = true) => {
  useEffect(() => {
    if (!isRunning) {
      run();
    }
    if (shouldRun) {
      callbacks.push(callback);
      return () => {
        callbacks.splice(callbacks.indexOf(callback), 1);
      };
    }
  }, [callback, shouldRun]);
};

export default useAnimationFrame;
