3

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?

2 Answers 2

4

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

myFunc = function (p1){setInterval(() => {
Sign up to request clarification or add additional context in comments.

Comments

3

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);
   }
}

Comments

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.