Search code examples
javascripttimerprototype

Timer does not want to stop by .prototype.stop


Why timer clock.start(); does not want to stop by using function clock.stop();.

I'm using typical function clearInterval in prototype stop to stop function start. Bur after calling clock.stop(); the timer in function clock.start(); does not stop.

I can not understand why...

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();

Solution

  • To solve a problem in a function clock.stop();, it is necessary to apply a closure similarly applied to the function clock.start();

    So we need to put the this._timer in the local variable and accessing directly to they by using the clouser method.

    in the Clock.prototype.start we did clouser

      this._render();
      var self = this;
    

    So we need to make the same in Clock.prototype.stop such

    var sef = this._timer;
    

    and use local variable sef in the timer function.

    So simple, but I understand it only now.

    Thanks to @elclanrs for a aiming :)