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?
CodePudding user response:
You should start to use either setTimeout
or setInterval
. while(true)
is not really a construct that you should ever use (in high-level contexts) in JavaScript, since it basically executes indefinitely and as fast as it can. You have to make sure to break;
it somewhere in the future to stop its execution.
In addition there is no way to garbage collect such type of code. You can destroy everything you want but your while(true)
construct will keep on looping.
What you possibly could do is this:
// Some component
{
data() {
return {
interval_id: undefined,
}
},
methods: {
someMethod() {
// Execute some code every 3 seconds (3000ms).
this.interval_id = setInterval(() => {
executeSomeCode();
}, 3000);
},
executeSomeCode() {
console.log('Executed');
}
},
// ...
Destroy() {
if(this.interval_id) {
clearInterval(this.interval_id);
}
}
}
Also note there is a typo in your code: Destory
-> Destroy
.
CodePudding user response:
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.