JSFiddle - React, Tailwind, and code Playground

by amindunited

HTML

<div id="circle_1" class="circle">
  
</div>

CSS

.circle {
  border-radius: 50%;
  background-color: grey;
  width: 100px;
  height: 100px;
}

JavaScript

class AnimationFrame {
  constructor(fps = 60, animate) {
    this.requestID = 0;
    this.fps = fps;
    this.animate = animate;
  }

  start() {
    let then = performance.now();
    const interval = 1000 / this.fps;
    const tolerance = 0.1;

    const animateLoop = (now) => {
      this.requestID = requestAnimationFrame(animateLoop);
      const delta = now - then;

      if (delta >= interval - tolerance) {
        then = now - (delta % interval);
        this.animate(delta);
      }
    };
    this.requestID = requestAnimationFrame(animateLoop);
  }

  stop() {
    cancelAnimationFrame(this.requestID);
  }

}

let frameCount = 0
const aFrame = new AnimationFrame(30, (e) => {
	frameCount++
	console.log('animation', e, frameCount);
});

aFrame.start()
setTimeout(() => {
	aFrame.stop()
}, 1000)

/*
const subject = document.querySelector('#circle_1.circle');

const fps = 30;
const animationRunner = () => {
  const interval = 1000 / fps;
	const tolerance = 0.01;
  let frames = 0;
  let then = performance.now();

	const requestAnimationHandler = (now) => {
		const delta = now - then;
    frames++;

    if (delta >= interval - tolerance) {
    	then = now - (delta % interval);
      console.log('frames', frames);
    	console.log('tick', delta);
  	}
    if (frames < 60) {
	    requestAnimationFrame(requestAnimationHandler)    
    }

  }
	requestAnimationFrame(requestAnimationHandler);
};
animationRunner();
*/
/*
const fps = 60;
let then = performance.now();
const interval = 1000 / fps;
const tolerance = 0.1;
const requestAnimationHandler = (now) => {
	const delta = now - then;
  if (delta >= interval - tolerance) {
    then = now - (delta % interval);
    // this.animate(delta);
    console.log('tick');
  }
  // requestAnimationFrame(requestAnimationHandler)
  console.log('???', then, now);
}

requestAnimationFrame(requestAnimationHandler);

*/