2017-06-14 7 views
1

私は、次々と実行したいアクションのリストを持っています。 ボクシングバッグのトレーニングを受けているとしましょう:間に遅延を含むアクションを実行する

ビープ音が鳴り、2秒後にインストラクターがアスリートに何をするかを伝えます( 'FOOTWORK')。インストラクターは15秒後、アスリートに何をしているのかを伝えるように指示します(テクニック)...これは1分が経過するまで続きます。その後、インストラクターはこの手順を3回繰り返します。

私はちょうどそれを行ういくつかのライブラリを構築しようとしていますが、私は各アクション間の遅延に問題があります。ここで私はこれまでやっていることです:

class Action{ 
    constructor(name = "Action", actualAction){ 
     this.name = name; 
     this.actualAction = actualAction; 
    } 

    run(){ 
     console.log("Executing Action: " + this.name); 
     this.actualAction(); 
    } 
} 

function repeat(times){ 
    var timesLeft = times; 
    return function(){ 
     timesLeft--; 
     return timesLeft > 0; 
    } 
} 

class SleepAction extends Action{ 
    constructor(ms, nextAction){ 
     super("Sleep " + ms); 
     this.ms = ms; 
     this.nextAction = nextAction; 
    } 

    run(){ 
     setTimeout(this.nextAction.run(), this.ms); 
    } 
} 

class Block extends Action{ 
    constructor(name = "Block", actions, repeat){ 
     super(name); 
     this.repeat = repeat; 
     this.instructions = actions; 
    } 

    run(){ 
     this.instructions.forEach(function(action) { 
      action.run(); 
     }); 

     if(this.repeat()){ 
      this.run(); 
     } 
    } 
} 

あなたは、私はこの作業を取得しようとするのsetTimeoutを使用していますが、すべてのアクションが、この例では、同時に実行することを伝えることができます:

var doNothing = new Action("Nothing", function(){}); 

var boxingBagPreset = new Block("Boxing Bag 15-15-15-15 3 Times", 
     [beepAction, 
     new SleepAction(2000, new Block("Tiny Pause", [ 
      new Action("FOOTWORK", textToSpeech("FOOTWORK")), 
      new SleepAction(15000, new Block("Sleep 15", [ 
       new Action("SPEED", textToSpeech("SPEED")), 
       new SleepAction(15000, new Block("Sleep 15", [ 
        new Action("POWER", textToSpeech("POWER")), 
        new SleepAction(15000, new Block("Sleep 15", [ 
         new Action("REST", textToSpeech("REST")), 
         new SleepAction(15000, new Block("Sleep 15", [doNothing], repeat(1))) 
        ], repeat(1))) 
       ], repeat(1))) 
      ] , repeat(1))) 
     ], repeat(1)))], 
    repeat(3)); 

これを機能させるには何を変更する必要がありますか?

答えて

2

問題は、すぐに関数を呼び出して、関数自体をsetTimeoutに渡すのではなく、結果を渡すことです。

これを試してみてください:原因道this

class SleepAction extends Action{ 
 
    constructor(ms, nextAction){ 
 
     super("Sleep " + ms); 
 
     this.ms = ms; 
 
     this.nextAction = nextAction; 
 
    } 
 

 
    run(){ 
 
     var func =() => this.nextAction.run(); 
 
     setTimeout(func, this.ms); 
 
    } 
 
}

が処理され、それを呼び出すsetTimeoutときthisは異なるものになりますので、あなただけのthis.nextAction.runを渡すことはできません。

この例では、thisをキャプチャするための新しい関数を作成しました。

+0

リピート()部分を除いて問題を解決していただきありがとうございます。それを機能させるためにチェーンを3回拡張することを除いて、あなたは何か推奨事項はありますか? (BEEP-BEEP-BEEP * 15s sleep * TECH-TECH-TECH ...などのようになります。 – Zarkopafilis

+1

@Zarkopafilis私は理解できませんが、新しい質問を作成して詳しく説明することができます。 – styfle

関連する問題