2016-03-05 92 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'); 
     } 
    }); 
}