How to Stop requestAnimationFrame in Javascript
March 27, 2020
How to cancel an animation running with requestAnimationFrame
The requestAnimationFrame() method in Javascript allows developers to run animations, usually at 60 times per second, by calling the same function over and over again each time the browser repaints. To break out of this loop we can use the cancelAnimationFrame() method on the window object. This method takes in the requestID of the requestAnimationFrame().
1.window.cancelAnimationFrame(requestID);
The requestID is returned from the requestAnimationFrame() every time it is run, so we can get this value by assigning it to a variable on each animation tick:
1.myRequestId = window.requestAnimationFrame(animate);
Where animate is the function that calls requestAnimationFrame() and runs the actual animation.
Example
1.let reqAnim, characterPosition;2....3.function animate() {4. ...5. characterPosition.x += 5;6. characterPosition.y += 5;7. reqAnim = window.requestAnimationFrame(animate);8.}9.10.function stopAnimation() {11. window.cancelAnimationFrame(reqAnim);12.}13.14.animate()
Where characterPosition is the animation, probably adding pxs to the CSS transform function translate().
More JavaScript Snippets
Popular Articles
I Can't Believe It's Not CSS: Styling Websites with SQL
Style websites using SQL instead of CSS. Database migrations for your styles. Because CSS is the wrong kind of declarative.

How I Built an Oreo Generator with 1.1 Sextillion Combinations
Building a web app that generates 1,140,145,285,551,550,231,122 possible Oreo flavor combinations using NestJS and TypeScript.

AI Model Names Are The Worst (tier list)
A comprehensive ranking of every major AI model name, from the elegant to the unhinged. Because apparently naming things is the hardest problem in AI.