-1

From what I have gathered from other posts it looks like it is not possible, but why can't i call a setInterval function (slightly shorter hand) like this?

tick: function() {
     var self = this;
     setInterval(this.calculateTime, 1000);
 }

I need to use the following.

  tick: function() {
    var self = this;
    setInterval(function(){this.calculateTime()}, 1000);
  }

Can anyone explain why this is the case and put my mind at ease?

Please see complete code below

var countdownTimer = {

  init: function(end) {
    this.endTime = new Date(end);
  },

  calculateTime: function(){
    this.now = new Date();
    this.difference = this.endTime - this.now;
    this.seconds = Math.floor(this.difference / 1000);
    this.minutes = Math.floor(this.seconds / 60);
    this.hours = Math.floor(this.minutes / 60);
    this.days = Math.floor(this.hours / 24);
    this.hours %= 24;
    this.minutes %= 60;
    this.seconds %= 60;
  },

  tick: function() {
    var self = this;
    setInterval(function(){this.calculateTime()}, 1000);
  }
}

countdownTimer.init('02/09/2016');
countdownTimer.calculateTime();
countdownTimer.tick();
  • There are dozens of versions of this question on SO, starting with those about those about how `this` works, such as [this one](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). –  Sep 01 '16 at 14:16
  • @torazaburo i understood `this` referred to the `window`, it was that i had to use `bind(this)` –  Sep 01 '16 at 14:21

1 Answers1

0

You can use bind for your purpose:

setInterval(this.calculateTime.bind(this), 1000);
Christoph
  • 1,631
  • 8
  • 19
  • thats the one Christoph, good knowledge! Will give you the green tick when I can –  Sep 01 '16 at 13:58
  • He didn't ask how to do it. He asked WHY HE NEEDS TO DO IT. –  Sep 01 '16 at 14:16
  • @torazaburo i was very satisfied with how the question was answered –  Sep 01 '16 at 14:30
  • Your very own question stated explicitly, *Can anyone **explain** why this is the case*. Anyway, with the advent of arrow functions, the cool boys would write this as `setInterval(() => this.calculateTime(), 1000);`. –  Sep 01 '16 at 14:32
  • @torazaburo i wouldn't know, I'm not a cool boy! :-) an explanation was what i was looking for, but a solution is even better. perhaps i phrased the question badly! Anyway, I'm really happy with the answer! thanks for your feedback, appreciate it –  Sep 01 '16 at 16:39