计时器不想通过 .prototype.stop 停止



为什么计时器clock.start();不想使用函数clock.stop();停止。

我在原型stop中使用典型的函数clearInterval来停止函数start。在函数clock.start();中调用clock.stop();计时器后 Bur 不会停止。

我不明白为什么...

function Clock(options) {
  this._template = options.template;
}
Clock.prototype._render = function() {
  var date = new Date();
  var hours = date.getHours();
  if (hours < 10) hours = '0' + hours;
  var min = date.getMinutes();
  if (min < 10) min = '0' + min;
  var sec = date.getSeconds();
  if (sec < 10) sec = '0' + sec;
  var output = this._template.replace('h', hours).replace('m', min).replace('s', sec);
  console.log(output);
};
Clock.prototype.start = function() {
  this._render();
  var self = this;
  this._timer = setInterval(function() {
    self._render();
  }, 1000);
};
Clock.prototype.stop = function() {
  setTimeout(function() {
    clearInterval(this._timer);
    console.log('Stop!'); // message is displayed, but timer in **this._timer** does not stop...
  }, 5000);
};
var clock = new Clock({
      template: 'h:m:s'
    });
clock.start();
clock.stop();

为了解决函数clock.stop();中的问题,有必要应用一个类似应用于函数 clock.start(( 的闭包;

因此,我们需要将this._timer放在局部变量中,并使用clouser方法直接访问它们。

Clock.prototype.start我们做了克劳瑟

  this._render();
  var self = this;

所以我们需要在这样的Clock.prototype.stop做同样的事情

var sef = this._timer;

并在定时器函数中使用局部变量 SEF。

这么简单,但我现在才明白。

感谢@elclanrs的瞄准:)

最新更新