2015-06-17 17 views
0

我試圖在第一個倒計時完成後顯示第二個倒計時。我正在使用流星。這是定時器:顯示一個接一個的JS倒計時

sec = 5 
@timer = setInterval((-> 
    $('#timer').text sec-- 
    if sec == -1 
    $('#timer').fadeOut 'fast' 
    sec= 
    timer 
    return 
), 1000) 

這是我如何把它 當模板被渲染我稱之爲setTimeout和倒計時顯示

Template.selector.rendered = -> 
    window.setTimeout(startGame, 5000) 
    timer 

當遊戲開始時,我需要一秒鐘的倒計時。我管理它是這樣的:

sec = 5 
sw = 0 
@timer = setInterval((-> 
    $('#timer').text sec-- 
    if sec == -1 
    if sw == 0 
     sw = 1 
     sec = 20 
    else if sw == 1 
    clearInterval timer 
    return 
), 1000) 

但是必須有更好的方法。

回答

0

如果你打算使用很多定時器,你可以創建一個對象來實現它。以下是取自here的示例您可以將其適應您的情況using custom events

ReactiveTimer = (function() { 

    // Constructor 
    function ReactiveTimer(interval) { 
     this._dependency = new Tracker.Dependency; 
     this._intervalId = null; 

     if(_.isFinite(interval)) 
      this.start(interval); 

    }; 

    ReactiveTimer.prototype.start = function(interval){ 
     var _this = this; 

     this._intervalId = Meteor.setInterval(function(){ 
      // rerun every "interval" 
      _this._dependency.changed(); 
     }, 1000 * interval); 
    }; 

    ReactiveTimer.prototype.stop = function(){ 
     Meteor.clearInterval(this._intervalId); 
     this._intervalId = null; 
    }; 

    ReactiveTimer.prototype.tick = function(){ 
     this._dependency.depend(); 
    }; 

    return ReactiveTimer; 
})();