Skip to content

Instantly share code, notes, and snippets.

@savitapatel
Last active March 9, 2023 18:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savitapatel/6ef3cf1b1ec1f6259236465f903d5706 to your computer and use it in GitHub Desktop.
Save savitapatel/6ef3cf1b1ec1f6259236465f903d5706 to your computer and use it in GitHub Desktop.
Animation using requestAnimationFrame
import React from 'react';
export function Animation() {
const animationByInterval = () => {
// Animation using setInterval
const start = Date.now();
const animatedText = document.querySelector('.myDiv');
const timer = setInterval(() => {
const interval = Date.now() - start;
animatedText.style.top = `${interval / 3}px`;
if (interval > 1000) clearInterval(timer);
}, 10);
};
let requestID;
const startAnimation = () => {
// Animation using requestAnimationFrame
let start = Date.now();
const animatedText = document.querySelector('.myDiv');
function playAnimation() {
const interval = Date.now() - start;
animatedText.style.top = `${interval / 3}px`;
if (interval > 1000) {
start = Date.now();
animatedText.style.top = 0;
}
requestID = requestAnimationFrame(playAnimation);
}
requestAnimationFrame(playAnimation);
};
const stopAnimation = () => cancelAnimationFrame(requestID);
return (
<div>
<button onClick={startAnimation}>Start Animation Using requestAnimationFrame</button>
<button onClick={stopAnimation}>Stop Animation Using requestAnimationFrame</button>
<button onClick={animationByInterval}>Animation Using setInterval</button>
<div className="myDiv">Demo Page</div>
</div>
);
}
.myDiv{
position: fixed;;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment