How to Stop requestAnimationFrame in Javascript

March 27, 2020

javascript

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().

js
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:

js
1.myRequestId = window.requestAnimationFrame(animate);

Where animate is the function that calls requestAnimationFrame() and runs the actual animation.

Example

js
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().