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

使用SetInterval()调用Javascript对象方法,javascript,object,methods,setinterval,momentjs,Javascript,Object,Methods,Setinterval,Momentjs,这里有一个 我正在尝试创建一个倒计时对象,该对象使用(我更喜欢使用Date()的插件) 然后我创建一个倒计时实例,如下所示: var countdown = new Countdown("January 1, 2014 00:00:00"); 但是,该函数似乎只运行一次。有什么想法吗?我应该改用setTimeout()吗?您应该传递对函数的引用,而不是它的执行结果。 此外,您还需要一些额外的“魔法”来以这种方式调用方法 var me = this; this.interval = setInt

这里有一个

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

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

var countdown = new Countdown("January 1, 2014 00:00:00");
但是,该函数似乎只运行一次。有什么想法吗?我应该改用setTimeout()吗?

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

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

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

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);
}

我更喜欢第二种方法-

而不是保存对
this
的引用,您可以使用
Function.bind
。是的,但它在较旧的浏览器中不起作用。问题中没有隐含的框架。似乎仍然不起作用,这里是更新的fiddle:我链接的答案是:
函数。bind
很容易填充。尝试
这个。在调用
setInterval
时,updateCountdown
。它似乎没有引用对象(抛出一个错误'cannotcallmethod'diff',of undefined):你需要这样做啊,好吧,我明白了,创建一个存储这个的局部变量。你想把它写下来作为一个答案,这样我就可以选择你的吗?
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);
}