'Logic inside component still execute even after component is destroyed VUEJS
I have a component inside which I'm using while loop to call the API every 3 sec to check status.
async download()
{
while(true) //->
{
await sleep(300);
console.log("still executing");
const status = await this.$store.dispatch("myaction",Id);
if(status.property === 2)
break;
}
}
Destroy()
{
console.log("component destroyed");
}
The problem is when i move away from component, i can see in console it is getting destroyed since it is calling Destroy() hook and print my log statement. but on the other hand it still prints my console statement inside while loop. Isn't it suppose to not run since component is destroyed or it is because of await sleep?.
just a additional info. the dispatch returns a promise within 100ms.
how can i prevent it to not execute as soon as i move away from component?
Solution 1:[1]
It's impossible for a framework to affect the way your own code is executed inside download function. The function prevents component instance from being garbage-collected when it runs, this is a demonstration of how memory leaks may work. It's developer's responsibility to stop the execution on unmount:
unmounted() {
this.isUnmounted = true;
},
...
async download() {
while(!this.isUnmounted) {
await sleep(300);
if (this.isUnmounted)
break;
...
It may be necessary to use checks in multiple places to reduce the amount of unwanted work. This is how it works in case of native promises and async..await. There may be additional ways to break the process early when using observables or a combination of cancelable promises and generators.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
