Last active
March 9, 2023 18:19
-
-
Save savitapatel/6ef3cf1b1ec1f6259236465f903d5706 to your computer and use it in GitHub Desktop.
Animation using requestAnimationFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.myDiv{ | |
position: fixed;; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment