这是一个 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() 吗?
最佳答案
您应该将引用 传递给函数,而不是其执行的结果。 此外,您需要一些额外的“魔法”才能以这种方式调用方法。
var me = this;
this.interval = setInterval(function () {
me.updateCountdown();
}, 1000);
关于javascript - 使用 SetInterval() 调用 Javascript 对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18263585/