2016-03-22 79 views
0

當用戶單擊元素時,它應該啓動超時並將starttime設置爲true。然後,如果用戶在定時器處於活動狀態時再次單擊元素,則應清除超時並重新啓動超時。但即時通訊仍然從第一個和下一個超時啓動控制檯。不應該讓我只有一個,最後一個創建?我已經在這裏嘗試了這個問題的例子How to reset timeout in Javascript/jQuery?重置超時值javascript

toggleCard: function(card){ 
       var Timer = null; 
       if(this.startTime){ 
        console.log('already activated'); 
        window.clearTimeout(Timer); 
        this.startTime = false; 
       } 

       this.startTime = true; 
       var Timer = setTimeout(function(){ 
//      this.taskCard = false; 
//      this.classCard = true; 
        console.log('old timer') 
       }.bind(this), 5000); 

回答

1

定義全局變量例如,

var myTimeOut = 0; 

那麼你的方法調用內部clearTimeout

toggleCard: function(card){ 
       clearTimeout(myTimeOut); 
       this.startTime = true; 
       myTimeOut = setTimeout(function(){ 
//      this.taskCard = false; 
//      this.classCard = true; 
        console.log('old timer') 
       }.bind(this), 5000); 
0

每次調用函數時要創建一個新的定時器變量,所以當你嘗試清除超時,定時器VAR不引用您創建的實際超時。

1

這樣做:

toggleCard: function(card) { 
    window.Timer = null; // <-----------declare timer globally here 
    if (this.startTime) { 
     console.log('already activated'); 
     window.clearTimeout(Timer); // <------- clear here if it is. 
     this.startTime = false; 
    } 

    Timer = setTimeout(function() { // <-------assign the setTimeout here 
     this.startTime = true; // <---------It has to be here. 
     // this.taskCard = false; 
     // this.classCard = true; 
     console.log('old timer') 
    }.bind(this), 5000); 
1

我認爲此代碼應滿足您的要求。

var timer = null; 
    var started = false; 
    toggleCard = function (card) { 
     if (started) { 
      console.log('Timer already active'); 
      window.clearTimeout(timer); 
     } else { 
      console.log('Timer active now'); 
      started = true; 
     } 

     timer = setTimeout(function() { 
      console.log('Timer elapsed! '); 
      started = false; 
     }.bind(this), 2000); 
    };