Manolis
Manolis

Reputation: 167

I can't target the correct scope inside my closure

I have a setInterval inside my closure but my I'm unable to target the variables inside the closure correctly. How so I target the variables correctly and stop the interval when counter has reached the finishTime?

 var counter = function() {
    return {
       myInterval: null,
       counter: 0,
       finishTime: 1000,
       startTimer: function() {
          this.myInterval = setInterval(this.repeat,10);
       },
       repeat: function() {
          if(this.counter==this.finishTime) clearInterval(this.myInterval);
          this.counter++;
       }
    }
 };

counter().startTimer();

Upvotes: 0

Views: 34

Answers (2)

Dmitry
Dmitry

Reputation: 7276

 var counter = function() {
    return {
       myInterval: null,
       counter: 0,
       finishTime: 1000,
       startTimer: function() {
          this.myInterval = setInterval(this.repeat.bind(this), 10);//need to bind the context here
       },
       repeat: function() {
           if(this.counter==this.finishTime)
           { 
               clearInterval(this.myInterval);
               console.log("finished")
            }
          this.counter++;
       }
    }
 };

counter().startTimer();

Upvotes: 1

fast
fast

Reputation: 885

Define everything in local scope (you may optionally assign repeat to the returned object, if you want to access it also from outside):

var Counter = function(finish)
{
 var count = 0;
 var myInterval = null;

 function repeat() {
  if(++count == finish)
   clearInterval(myInterval);
 }

 return {
      getCount: function() { return count; },
      startTimer: function() { myInterval = setInterval(repeat,10); return this; },
      repeat: repeat
 };
};

var counter = new Counter(1000).startTimer();

Upvotes: 1

Related Questions