簡體   English   中英

有沒有辦法查看 function 是否已執行完畢?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM