Why the timer setTimeout returns the first value “2”

Although your code works as expected, it could be that under some conditions you wouldn’t print all numbers. It might be better to check the counter value and then clear the interval at that time (timing in javascript is not really that precise as you might hope it to be)

You could try to do it like this though, to make sure that your interval can only run once, and that you don’t exceed your max value.

function Counter(start, maxValue, ticks) {
  this.value = start || 0;
  this.max = maxValue;
  this.ticks = ticks;
  var interval;
  
  this.stop = function() {
    if (!interval) {
      return;
    }
    clearInterval(interval);
    console.log('stopped counter');
  };
  
  this.increase = function() {
    this.value++;
    console.log(this.value);
    if (this.value >= this.max) {
      this.stop();
    }
  };
  
  this.start = function() {
    if (interval) {
      return;
    }
    console.log('starting counter');
    interval = setInterval(this.increase.bind(this), this.ticks || 0);
  };
}

var counter = new Counter(0, 20, 100);
counter.start();

Leave a Comment