Reputation: 157
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
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
Reputation: 657078
Just use arrow functions () => {}
instead of function() {}
to make this
point to the current class instance
myFunc = function (p1){setInterval(() => {
Upvotes: 4