2016-12-30 6 views
0

私は基本クラスTimerとその中にいくつかのメソッドを持っています。私の考えは単純です、私はタイマーを実行するための基本的なクラスが必要です。基本クラスのインスタンスとしてのさまざまなタイマーの多く。しかし、私はこのように私のがらくたを実行しようとすると、私は.startTimer.runjavascriptでタイマーを実行する

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); }); 

あなたのコードの残りの部分は、あなたが望むものをないこと提供する、それが行う必要がありますトリック。

のsetTimeoutのような時間間隔で無限の実行を呼び出すことが可能なのJavaScriptのsetInterval関数で
+1

'setTimeout(this.run(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>

、しかしのsetTimeoutはのsetInterval一度実行しなくなります。 clearInteval( - inteval timer variable--)を使用してsetIntervalを制御できます。

関連する問題