Reputation: 131
I have an angular 6 strange problem.
I am using setTimeout and clearTimeout functions to start/cancel the timeout. However this sometimes works, and sometimes doesn't. Even if the user triggers an (click) event and the clearTimeout is run, sometimes it forces player to draw two cards.
Here is the code
//an event that says we must call uno
this._hubService.mustCallUno.subscribe(() => {
this.mustCallUno = true;
this._interval = window.setInterval(() => {
this.countdown -= 100;
}, 100);
this._timer = window.setTimeout(() => {
if (this.mustCallUno) {
this.drawCard(2);
this.callUno();
}
}, 2000);
});
// a function player calls from UI to call uno and not draw 2 cards
callUno() {
this.mustCallUno = false;
window.clearTimeout(this._timer);
window.clearInterval(this._interval);
this.countdown = 2000;
}
So even if the player calls callUno() function, the setTimeout is executed. Even worse, the code goes through the first if check inside the setTimeout if( this.mustCallUno)
which by all means should be false since we just set it to false when we called callUno() function this.mustCallUno = false;
.
I used setTimeout (returns NodeJS.Timer) before window.setTimeout and the result was the same.
Upvotes: 1
Views: 21258
Reputation: 1481
You're using angular6+, so I suggest you to use reactive programming library such as rxjs
I made you a small example here.
Upvotes: 2
Reputation: 2452
Check for the possibility where function in this._hubService.mustCallUno.subscribe
is run twice or multiple times, usually initially which you might not be expecting. Put a logger in function passed to mustCallUno.subscribe
and callUno
.
In this case what might be happening is this._timer
and this._interval
will have a different reference while the old references they hold, were not cleared because callUno
is not called or is called less number of times than the callback in subscribe.
Upvotes: 1