0

这是我从咖啡转换而来的 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 中,并且命名空间$为下划线的混合方法

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
4

2 回答 2

3

在您清除它之前,您已经返回了该函数。先清除,然后返回。

reset_timer: function() {
  clearInterval(this.timer);
  return this.set({
    time_to_complete: 0
  });
}

至于 的值this,要小心,因为this它是由你调用它的方式决定的,而不是它的声明方式。

于 2013-05-08T21:31:38.943 回答
0

好的,如果我在 set_timer 函数的开头添加它,它就可以工作!

if (this.timer !== null) {
  clearInterval(this.timer);
}
于 2013-05-08T22:23:31.163 回答