使用 SetInterval() 调用 Javascript 对象方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18263585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call Javascript Object Method with SetInterval()
提问by dougmacklin
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() 吗?
采纳答案by fbynite
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
我更喜欢第二种方法 -小提琴
回答by kirilloid
You should pass a referenceto 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);