Home > Back-end >  Is there a way to see if a function is done executing?
Is there a way to see if a function is done executing?

Time:12-13

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.

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.

CodePudding user response:

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());

  • Related