How to Stop requestAnimationFrame in Vuejs / Javascript

coolgoose

Alexandru Bucur

Posted on July 20, 2019

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
💖 💪 🙅 🚩
coolgoose
Alexandru Bucur

Posted on July 20, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related