这是我从咖啡转换的js:
set_timer: function() {
var _this = this;
return this.timer = setInterval(function() {
_this.set({
time_to_complete: _this.get("time_to_complete") + 1
});
if (_this.get("time_to_complete") > 3) {
console.log("End of clear.");
return _this.reset_timer(_this.timer);
}
}, 1000);
},
reset_timer: function() {
clearInterval(this.timer);
return this.set({
time_to_complete: 0
});
}
然后它被称为:
this.model.set_timer();
由于某些原因,这不清楚,我的间隔不断产生console.log
的
这是同样错误的另一个例子,但是在Coffeescript中,namedspaced到$
作为下划线的mixin方法
set_timer: (model) =>
$.timer = setInterval =>
model.set time_to_complete: model.get("time_to_complete") + 1
if model.get("time_to_complete") > 3
console.log "End of clear."
_.reset_timer model
, 1000
reset_timer: (model) ->
clearInterval $.timer
model.set time_to_complete: 0
答案 0 :(得分:3)
在清除之前,您已经返回了该功能。首先清除它,然后返回。
reset_timer: function() {
clearInterval(this.timer);
return this.set({
time_to_complete: 0
});
}
至于this
的值,要小心,因为this
取决于你调用它的方式,而不是它的声明方式。
答案 1 :(得分:0)
好的,如果我在set_timer函数的开头添加它,它就可以了!
if (this.timer !== null) {
clearInterval(this.timer);
}