Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to see if a function is done executing?

I have a class with many objects, and I need to see if the function for each of these objects is done being executed.

I have tried using an array, where I keep track of each function’s status, but it’s pretty inefficient. Are there any other ways to do this?

The objects are for dialogue in a small game I’m making.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is the example of the code I have right now:

var functionExecuted = [false, false, false, false, false, false];

The function in the class takes a parameter of where the object’s function is in the array. At the end of the function in the class, I do this:

functionExecuted[this.funcExecutedIndex] = true;

And then later once the function is finished executed, I continue on with the program

The reason why I have to check for this is because I’m working with the HTML canvas, and if I don’t wait for the function to finish being executed, it draws on top of it.

>Solution :

functions in JS are just objects, as such you can store them in a Set.

The nice thing about using a Set’s, it avoids you having to maintain that funcExecutedIndex, and you can use it to find out if a particular function has been executed, and it’s size can be used to check if all functions have been executed..

Below is a simple example.

class Procs {
  executed = new Set();
  one() {
    this.executed.add(this.one);
  }
  two() {
    this.executed.add(this.two);
  }
  whatsExecuted() {
    console.log('one executed: ' + this.executed.has(this.one));
    console.log('two executed: ' + this.executed.has(this.two));
  }
  allExecuted() {
    return this.executed.size === 2;
  }
}


const procs = new Procs();
procs.whatsExecuted();
console.log('---');

procs.one();
procs.whatsExecuted();
console.log('all done: ' + procs.allExecuted());

console.log('---');

procs.two();
procs.whatsExecuted();
console.log('all done: '+ procs.allExecuted());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading