0

私はゲームに取り組んでおり、それぞれの間に 2 秒の一時停止を入れて特定のことを実行したいと考えています。

jQuery でラップされた選択ではないため、delay() を使用できません。以下のコードの問題は、一時停止の前に RedFlash() 関数が発生していることです。たぶん、配列から関数を実行し、それぞれの間に 2 秒間の一時停止を行う 1 つの大きな関数が必要です。

// Attack Phase
function attackPhase() {
  animateMessage("You slash with your weapon!", "red");
  window.setTimeout(function() {
     animateMessage("You dealt 15 damage!", "red");
  }, 2000);
  window.setTimeout(function() {
     $('.card_hp').redFlash();
  }, 2000);    
}

要約すると、次のとおりです。

// action
// pause 2 seconds
// action
// pause 2 seconds
// action
// pause 2 seconds
// and so on

一度一時停止する方法についてはいくつかの回答が見つかりましたが、複数回一時停止して各アクションを 2 秒間待機させる方法は見つかりませんでした。

4

2 に答える 2

2

これは、アクションをキューに入れ、2秒間隔で次々に実行する方法の例です。また、次にアクションをアクティブ化すると、同じキューに投稿され、前のすべてのアクションが完了するまで開始されません。

var queue = [],
    timer,
    processQueue,
    animateMessage,
    attackPhase;

processQueue = function processQueue(force) {
  if(!timer || force) {
    timer = setTimeout(function() {
      if(queue.length > 0) {
        queue.splice(0,1)[0]();
        processQueue(true);
      } else {
        timer = null;
      }
    }, 2000);
  }
};

animateMessage = function animateMessage(msg, color) {
  console.log(msg);
};

attackPhase = function attackPhase() {
  queue.push(function(){
    animateMessage("You slash with your weapon!", "red");
  });
  queue.push(function() {
    animateMessage("You dealt 15 damage!", "red");
  });
  processQueue();
};

attackPhase();
attackPhase();

これが実際の例ですhttp://jsbin.com/akagin/4/edit

于 2013-03-12T21:53:18.010 に答える
2

問題は、基本的に両方のsetTimeout()機能を同時に開始しているためです。

// Attack Phase
  function attackPhase() {
    animateMessage("You slash with your weapon!", "red");
    window.setTimeout(function() {
          animateMessage("You dealt 15 damage!", "red");
          window.setTimeout(function() {
                $('.card_hp').redFlash();
           }, 2000);
    } , 2000);
 }

注: これはあまりよく書かれたコードではありません。var必要に応じて設定できるように、setTimeouts を a に設定するclearTimeout(var)必要があります。他にも考慮すべきことがたくさんありますが、この質問の範囲を超えています。

于 2013-03-12T20:36:12.343 に答える