I have a method that is frequently called and contains several "await" parts with code following them. However, in some cases, these promises may remain unresolved, causing the code after the "awaits" to never be executed. I'm concerned about what happens to this unreached code - will it accumulate in memory and eventually cause lag on the site due to frequent method calls?
Here's an example of the code:
class Test {
constructor() {
this.runTest();
}
playAnimation() {
return new Promise((resolve) => {
this.timeOut = setTimeout(() => {
console.log('Anim completed.');
resolve();
}, 3000);
});
}
stopAnimation = () => {
document.body.removeEventListener('click', this.stopAnimation);
clearTimeout(this.timeOut);
};
async method() {
await this.playAnimation();
// If clicked twice, this loop will never execute as the promise never resolves.
for (let i = 0; i < 1000; i++) {
// Do something
}
console.log('Promise resolved');
}
runTest = () => {
document.body.removeEventListener('click', this.runTest);
document.body.addEventListener('click', this.stopAnimation);
document.body.addEventListener('click', this.runTest);
this.method();
}
}
new Test();