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

dou*_*lin 7 javascript methods object setinterval momentjs

这是一个小提琴.

我正在尝试创建一个使用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);
}
Run Code Online (Sandbox Code Playgroud)

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

var countdown = new Countdown("January 1, 2014 00:00:00");
Run Code Online (Sandbox Code Playgroud)

但是这个功能似乎只运行一次.有任何想法吗?我应该使用setTimeout()吗?

kir*_*oid 15

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

var me = this;
this.interval = setInterval(function () {
    me.updateCountdown();
}, 1000);
Run Code Online (Sandbox Code Playgroud)


fby*_*ite 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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