8

这是一个小提琴

我正在尝试创建一个使用moment.js的倒计时对象(我更喜欢使用 Date() 的插件)

var Countdown = function(endDate) {
    this.endMoment = moment(endDate);

    this.updateCountdown = function() {
        var currentMoment, thisDiff;

        currentMoment = moment();
        thisDiff = (this.endMoment).diff(currentMoment, "seconds");

        if (thisDiff > 0)
            console.log(thisDiff);
        else {
            clearInterval(this.interval);
            console.log("over");
        }
    }

    this.interval = setInterval(this.updateCountdown(), 1000);
}

然后我创建一个倒计时的实例,如下所示:

var countdown = new Countdown("January 1, 2014 00:00:00");

然而,该功能似乎只运行一次。有任何想法吗?我应该改用 setTimeout() 吗?

4

2 回答 2

15

You should pass a reference to function, not the result of its execution. Also, you need some additional "magic" to call a method this way.

var me = this;
this.interval = setInterval(function () {
    me.updateCountdown();
}, 1000);
于 2013-08-15T23:32:00.823 回答
4

您可以将this上下文存储为局部变量,如下所示:

var Countdown = function(endDate) {
  var self = this;
  this.endMoment = moment(endDate);

  this.updateCountdown = function() {
      var currentMoment, thisDiff;

      currentMoment = moment();
      thisDiff = (self.endMoment).diff(currentMoment, "seconds");

      if (thisDiff > 0)
          console.log(thisDiff);
      else {
          clearInterval(self.interval);
          console.log("over");
      }
  }

  this.interval = setInterval(this.updateCountdown, 1000);
}

或者您可以直接使用变量,例如:

var Countdown = function(endDate) {
  var endMoment = moment(endDate);

  this.updateCountdown = function() {
      var currentMoment, thisDiff;

      currentMoment = moment();
      thisDiff = (endMoment).diff(currentMoment, "seconds");

      if (thisDiff > 0)
          console.log(thisDiff);
      else {
          clearInterval(interval);
          console.log("over");
      }
  }

  var interval = setInterval(this.updateCountdown, 1000);
}

我更喜欢第二种方法 -小提琴

于 2013-08-15T23:54:34.170 回答