简体   繁体   English

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

[英]Call Javascript Object Method with SetInterval()

Here is a fiddle . 这是一个小提琴

I'm trying to create a countdown object that uses moment.js (a plugin that I prefer over using Date()) 我正在尝试创建一个使用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);
}

I then create a instance of the countdown like so: 然后我创建一个倒计时的实例,如下所示:

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

However the function only seems to run one time. 但是这个功能似乎只运行一次。 Any ideas? 有任何想法吗? Should I be using setTimeout() instead? 我应该使用setTimeout()吗?

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

You can either store your this context as a local variable like the following: 您可以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);
}

Or you can just use your variables directly such as: 或者您可以直接使用您的变量,例如:

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

I prefer the second approach - fiddle 我更喜欢第二种方法 - 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM