简体   繁体   English

有没有办法查看 function 是否已执行完毕?

[英]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.我有一个包含许多对象的 class,我需要查看每个对象的 function 是否已完成执行。

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. class 中的 function 以对象的 function 在数组中的位置作为参数。 At the end of the function in the class, I do this:在 class 中的 function 结束时,我这样做:

functionExecuted[this.funcExecutedIndex] = true;

And then later once the function is finished executed, I continue on with the program然后,一旦 function 执行完毕,我继续执行该程序

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.我必须检查这个的原因是因为我正在使用 HTML canvas,如果我不等待 function 完成执行,它就会在它上面绘制。

functions in JS are just objects, as such you can store them in a Set. JS 中的函数只是对象,因此您可以将它们存储在一个集合中。

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..使用 Set 的好处是,它避免了您必须维护funcExecutedIndex ,并且您可以使用它来确定特定的 function 是否已被执行,并且它的大小可用于检查是否所有函数都已执行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM