0

I want to do a timer as an object.

The problem is that Im getting NAN instead of the increasing value of counter when I run the my Interval Method.

I understand that Im probably setting the this wrong, but I dont understand what exactly Im doing wrong with the this here.

What am I doing wrong?

timer = {
            count: 0,

            addASecond: function()  {
                this.count++;
                console.log(this.count);
            },

            myInterval() {setInterval(this.addASecond,1000);}

        }

        timer.myInterval();     

    </script>

Thanks in advance

Fabian

Fabian Andiel
  • 321
  • 1
  • 13

1 Answers1

1
myInterval() {setInterval(this.addASecond.bind(this),1000);}

or

myInterval() {setInterval(() => this.addASecond(),1000);}
satanTime
  • 12,631
  • 1
  • 25
  • 73
  • It works but I dont understand it. Where is the "this" pointing at when I call the method without your changes? Whats the element that doesn´t work in timer.myInterval()? – Fabian Andiel Mar 24 '20 at 10:48
  • 1
    @Fabian `this` is determined by how the function is *called*; the way you're passing the callback to `setInterval`, it can only be called without `this` context. Read the duplicate for details. – deceze Mar 24 '20 at 10:55
  • when you pass it as this.addASecond (not executing, just passing), then you pass a pointer to the function. you can test it like that var myFunc = timer.addASecond; then when you call myFunc(), this inside of it is not "timer", but current "this" (global object if you are outside of a class context). that's why we need to bind the call to a context, or to avoid reference to the function and create an arrow function to call it. – satanTime Mar 25 '20 at 10:46