[英]Is there a way to see if a function is done executing?
我有一个包含许多对象的 class,我需要查看每个对象的 function 是否已完成执行。
我曾尝试使用一个数组来跟踪每个函数的状态,但效率很低。 还有其他方法可以做到这一点吗?
这些对象用于我正在制作的小游戏中的对话。
这是我现在拥有的代码示例:
var functionExecuted = [false, false, false, false, false, false];
class 中的 function 以对象的 function 在数组中的位置作为参数。 在 class 中的 function 结束时,我这样做:
functionExecuted[this.funcExecutedIndex] = true;
然后,一旦 function 执行完毕,我继续执行该程序
我必须检查这个的原因是因为我正在使用 HTML canvas,如果我不等待 function 完成执行,它就会在它上面绘制。
JS 中的函数只是对象,因此您可以将它们存储在一个集合中。
使用 Set 的好处是,它避免了您必须维护funcExecutedIndex
,并且您可以使用它来确定特定的 function 是否已被执行,并且它的大小可用于检查是否所有函数都已执行。
下面是一个简单的例子。
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.