0

I am having trouble debugging the increment and tick methods of my Clock class. The seconds property of Clock should be incremented by 1 every second, but instead seconds is throwing a NaN error.

The goal of increment is to increment the seconds on the Clock instance by 1 each time it is called. Tick calls the increment method every second to make this possible.

function Clock() {
  this.seconds = 0;
}

Clock.prototype.increment = function() {
  this.seconds = this.seconds + 1;
  console.log('Seconds: ' + this.seconds);
};

Clock.prototype.tick = function() {
  setInterval(this.increment, 1000);
};

var timex = new Clock();

timex.tick();
Mjuice
  • 1,288
  • 2
  • 13
  • 32

2 Answers2

0

this is the window when you call it with setTimeout.

setInterval(this.increment.bind(this), 1000);
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

The issue is that within your setInterval handler, this no longer points to your Clock object, but to the global namespace. The easiest solution is just to bind this to this.increment:

Clock.prototype.tick = function() {
  setInterval(this.increment.bind(this), 1000);
};

See also: Javascript setInterval and `this` solution

Community
  • 1
  • 1
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63