簡體   English   中英

使用SetInterval()調用Javascript對象方法

[英]Call Javascript Object Method with SetInterval()

這是一個小提琴

我正在嘗試創建一個使用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()嗎?

您應該傳遞對函數的引用 ,而不是它的執行結果。 此外,您需要一些額外的“魔法”來以這種方式調用方法。

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

您可以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);
}

我更喜歡第二種方法 - 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM