0

Say I have an object:

var myObj = function {
this.count = 0;
}

myObj.prototype {
   setCount : function() {
       var interval = setInterval(function() {
           this.count++;
       }, 500);
   }
}

The issue is count is always undefined within the setInterval so i can never increment the count variable within myObj to be something other than 0.

2 Answers 2

4

this changes depending on the function being called (and how it said function is called).

The anonymous function you pass to setInterval is a different function.

Copy the value to a non-magic variable first.

   setCount : function() {
       var that = this;
       var interval = setInterval(function() {
           that.count++;
       }, 500);

See the this problem in the documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

or use bind
0

setInterval() runs in the scope of the browser window, so this.count refers to window.count which does not exist.

1 Comment

How to grab a reference to the actual count I want and then increment it with setInterval? Or is there some other means besides setInterval?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.