2016-03-05 45 views
2

我有一些像這樣的代碼:

function updateCounter(){ 
    $({someValue: 2*60*1000}).animate({someValue: 0}, { 
     duration: 2*60*1000, 
     easing:"linear", 
     step: function() { 
     //dosomething 
     }, 
     complete: function() { 
     // 2 minutes end 
     alert('game_over'); 
     } 
    }); 
} 

通常情況下,game over會後2分鐘提醒。但是如果我想在計數器結束之前殺死計數器呢?我有一個這樣的想法:在complete回調函數中,檢查一個變量,如果它的值爲true,則返回該函數。它適用於我,但有什麼辦法可以直接刪除回調函數嗎?就像removeEventListener()

無法通過Google或jQuery網站找到它。

+1

看看jQuery中的'.stop()'函數。 [jQuery API:.stop()](https://api.jquery.com/stop/) – shamsup

+0

我的代碼沒有綁定到DOM,所以如何阻止它? –

+0

你爲什麼要用動畫製作而不是settimeout或setinterval? –

回答

1

因爲您的對象沒有以任何方式綁定到DOM,所以最好的方法可能是在創建對象時將其存儲在變量中。這樣,只要需要操作它,就可以通過變量名訪問該對象。

function updateCounter(){ 
    var timer = $({someValue: 2*60*1000}); 

    timer.animate({someValue: 0}, { 
     duration: 2*60*1000, 
     easing:"linear", 
     step: function() { 
      if(yourCondition == true){ // condition for killing timer 
       // do stuff when your timer is going to end 
       // stops animation, default doesn't perform complete callback 
       timer.stop(); 
      } 
      // normal step function events 
     }, 
     complete: function() { 
      // 2 minutes end 
      alert('game_over'); 
     } 
    }); 
}