Daniel Gontar
Daniel Gontar

Reputation: 157

Using setInterval function inside angular 2 Component

I am trying to use setInterval inside: class SignupComponent so, function () { } can change values to 2 vars of the class which are outscope of function() {} but inscope of the class SignupComponent and I fail. I am using setInterval so I can activate some animation in cycles. Here is the code:

export class SignupComponent  {
      state = 'normal';
      state2 = 'normal';
      v1 = 0;
      myFunc = function (p1){setInterval(function(){
           p1++;
           if (p1%4==0)
        {
            console.log(this.state2);
            this.state == 'normal' ? this.state = 'disappear': this.state
               = 'normal';
            this.state2 == 'normal' ? this.state2 = 'appear': this.state2
               = 'normal' 
        }
    }, 1000)};

Problem is that this.state , this.state2 inside setInterval(function(){.... } Don't refer to state , state2 outside the scope but in he scope of the class. why can't I do this closure? Is there a way to connect those couple of vars so values will be updated?

Upvotes: 3

Views: 6154

Answers (2)

Long Field
Long Field

Reputation: 878

setTimeout/setInterval should be called in this way(for angular user):

export class demo implements OnDestroy{
   private _setTimeoutHandler: any;
   private _setIntervalHandler: any;

   mymethod1(){
       this._setTimeoutHandler = setTimeout(() => {
       // my to do 
       }, 100);
   }

   mymethod2(){
      this._setIntervalHandler = setInterval(() => { 
          myTimer() 
     }, 100);
   }


   ngOnDestroy() {
      clearTimeout(this._setTimeoutHandler)}
      clearInterval(this.__setIntervalHandler);
   }
}

Upvotes: 3

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657078

Just use arrow functions () => {} instead of function() {} to make this point to the current class instance

myFunc = function (p1){setInterval(() => {

Upvotes: 4

Related Questions