0

I'm trying to display a second countdown after the first one finishes. I'm using meteor. This is the timer:

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

This is how I call it When the template is rendered I call a setTimeout and a countdown displays

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

When game starts I need a second countdown. I managed it like this:

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)

But there has to be a better way.

1 Answers1

0

If you plan to use many timers, you could make an object to achieve that. Here is an example taken from here You could adapt it to your case 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;
})();
Community
  • 1
  • 1
Billybobbonnet
  • 3,156
  • 4
  • 23
  • 49