DEV Community

Alexandru Bucur
Alexandru Bucur

Posted on • Originally published at alexandrubucur.com

How to Stop requestAnimationFrame in Vuejs / Javascript

TLDR:

let id = window.requestAnimationFrame(fancyFunctionHere)
window.cancelAnimationFrame(id);
Enter fullscreen mode Exit fullscreen mode

Now for the longer version. Technically in Vue.js you might have components/mixins that use window.requestAnimationFrame. Since the fancyFunctionHere is used as a callback, everytime you call window.requestAnimationFrame you are going to get a new id that you should use on the destroy method to stop it.

Unfortunately this is not imediately clear on MDN so hopefully my documentation edit with the comment in the code example goes trough.

{
    created() {
        this.id = window.requestAnimationFrame(
            this.fancyFunctionHere
        );
    },

    destroyed() {
        window.cancelAnimationFrame(this.id);
        this.id = undefined;
    },

    data() {
        return {
            id: undefined
        }
    }

    methods: {
        fancyFunctionHere() {

        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
anpos231 profile image
anpos231

I did not know you could stop it.

Collapse
 
timkor profile image
Timkor

Just curious: what situations require cancelling a requested animation on destroy just a few milliseconds after creation?

I don't get it.

Collapse
 
coolgoose profile image
Alexandru Bucur

I don't understand what you mean unfortunately.

Destroy is the vue method for when the component isn't active on the page. And we are just doing cleanup, it's not a few milliseconds after.

Collapse
 
timkor profile image
Timkor • Edited

No exactly. You are now cancelling an on create requested animation frame on destroy. But the animation frame will pretty much all the times already being fired.

I was just wondering if you could provide a scenario where a Vue component is created and deleted within a few milliseconds.

Thread Thread
 
elliott_regan profile image
Elliott Regan • Edited

The benefit could be when this.fancyFunctionHere kicks off a recursive loop, like an animation.

fancyFunctionHere() {
    this.id = requestAnimationFrame(this.fancyFunctionHere);
}