TLDR:
let id = window.requestAnimationFrame(fancyFunctionHere)
window.cancelAnimationFrame(id);
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() {
}
}
}
Top comments (5)
I did not know you could stop it.
Just curious: what situations require cancelling a requested animation on destroy just a few milliseconds after creation?
I don't get it.
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.
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.
The benefit could be when this.fancyFunctionHere kicks off a recursive loop, like an animation.