2016-12-27 113 views
-1

我製作了一個恩賜系統,玩家在此獲得一個隨機恩賜/ buff達30秒,然後它自行消失。我有最初的好處,它持續30秒,然後自行移除。我把福音名稱「Healing Boon」推到一個空的player.boons = []陣列。Javascript:如何取消setTimeout函數?

但是我反過來遇到了困難。讓我們說敵人想要「減化」我的角色,並立即刪除這個恩賜。那麼,因爲我的恩賜倒數計時器持續30秒,即使我看上去已經移除,它仍會繼續工作,直到30秒結束。 (我仍然保持健康長達30秒)。

我把這歸功於setTimeout函數。如果我輸入30秒,即使稍後在線下(比如說5-10秒),也可以在setTimeout = 0;之後繼續下一個30秒。它只在最初的第二次嘗試是setTimeout設置爲0.但這不是我想要的。我想要一個系統完全停止它的區域,並移除它給玩家的所有當前健康增益。

function applyBoonHealing(){ 
    var blessedWind = setInterval(function(){ 
     player.cc.hp += 1; 
     dom.setText("healthcounter", player.cc.hp); 
    }, 1000); 
    player.boons.push("Healing Boon"); 
    postPlayerStatusEffectImage("images/lowerstrengthicon.jpg", "buff", "0", "2", "no"); 
    dom.setText("healthcounter", player.cc.hp); 

    setTimeout(clearBoon, 30000); 
     function clearBoon(){ 
      clearInterval(blessedWind); 
     if (player.boons.includes("Healing Boon", 0)){ 
      var arrayIndex = player.boons.indexOf("Healing Boon", 0); 
      player.boons.splice(arrayIndex, 1); 
     }   
      dom.setText("healthcounter", player.cc.hp); 
      postPlayerStatusEffectImage("images/lowerstrengthicon.jpg", "buff", "0", "2", "yes"); 
     } 
} 

回答

3

clearTimeout()方法是解決這個問題的:

var boonHandle = setTimeout(clearBoon, 30000); 
(...) 
clearTimeout(boonHandle); //To cancel your timer 
0

clearTimeout是一個情況下,停止超時,請參見下面

function myStopFunction() { 
    clearTimeout(myVar); 
}