使用SetInterval()调用Javascript对象方法

时间:2013-08-15 23:30:20

标签: javascript object methods setinterval momentjs

这是 fiddle

我正在尝试创建一个使用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()吗?

2 个答案:

答案 0 :(得分:14)

您应该将引用传递给函数,而不是它的执行结果。 此外,您需要一些额外的“魔法”来以这种方式调用方法。

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

答案 1 :(得分: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);
}

我更喜欢第二种方法 - fiddle