2016-12-30 21 views
0

我有基類Timer和其中的幾個方法。我的想法很簡單,我需要一個基本類來運行計時器。很多不同的定時器都是基類的實例。但我不知道我應該如何傳遞方法作爲參數.startTimer.run在javascript上運行計時器

function Timer(interval) { 
     this.isTimerRuns = false; 
     this.timerId = 0; 
     this.interval = interval; 
    } 

Timer.prototype.run = function (foo) { 
    if(this.isTimerRuns){ 
     foo(); 
     setTimeout(this.run(foo), this.interval); 
    } 
    else{ 
     this.stopTimer(); 
    } 
}; 

Timer.prototype.startTimer = function (foo) { 
    this.timerId = setTimeout(this.run(foo), this.interval); 
    this.isTimerRuns = true; 
}; 

Timer.prototype.stopTimer = function() { 
    clearInterval(this.timerId); 
    this.isTimerRuns = false; 
    this.timerId = 0; 

}; 

Timer.prototype.ajaxCall = function (url, method, successFunc, errorFunc) { 
    $.ajax({ 
     url: url, 
     type: method, 
     success: function (data) { 
      var respond = JSON.parse(data); 
      successFunc(respond); 
     }, 
     error: function() { 
      if(errorFunc != null){ 
       errorFunc(); 
      } 
     } 
    }); 
}; 

裏面當我嘗試運行我的廢話是這樣的:

var t = new Timer(10000); 
    t.startTimer(t.ajaxCall("/123", "POST", test2, null)); 

function test2(resp) { 
    console.log(resp + '!'); 
} 

它只運行一次,然後停止。我該如何解決它?

這樣做::

回答

3

它,因爲你執行,而不是把它當作一個參數的函數運行一次

t.startTimer(function() { t.ajaxCall("/123", "POST", test2, null); }); 

提供你的代碼的其餘部分你想要做什麼,是應該做的訣竅。

+1

看起來像'setTimeout(this.run(foo),this.interval)需要修復... – Teemu

+0

是的。好點。以及run方法不保留超時引用。所以也許整個班級需要一些反思。 –

0

function Timer(interval) { 
 
     this.isTimerRuns = false; 
 
     this.timerId = 0; 
 
     this.interval = interval; 
 
    } 
 
Timer.prototype.startTimer = function (foo) { 
 
\t this.isTimerRuns = true; 
 
    this.timerId = setInterval(foo, this.interval); 
 
    
 
}; 
 

 
Timer.prototype.stopTimer = function() { 
 
\t clearInterval(this.timerId); 
 
    this.isTimerRuns = false; 
 
    this.timerId = 0; 
 

 
}; 
 

 
Timer.prototype.ajaxCall = function (url, method, successFunc, errorFunc) { 
 
    $.ajax({ 
 
     url: url, 
 
     type: method, 
 
     success: function (data) { 
 
      var respond = JSON.parse(data); 
 
      successFunc(respond); 
 
     }, 
 
     error: function() { 
 
      if(errorFunc != null){ 
 
       errorFunc(); 
 
      } 
 
     } 
 
    }); 
 
}; 
 

 
function test2(resp) { 
 
    console.log(resp + '!'); 
 
} 
 

 
    var t = new Timer(1000); 
 
    t.startTimer(function(){t.ajaxCall("/123", "POST", test2, null)});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

在JavaScript的setInterval函數可以調用與像setTimeout的間隔時間無限的執行,但setTimeout的會一次,但不執行的setInterval。我們可以通過使用clearInteval( - inteval timer variable--)來控制setInterval。

相關問題