Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  170] [ 4]  / answers: 1 / hits: 17066  / 5 Years ago, fri, august 9, 2019, 12:00:00

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.


More From » angular

 Answers
2

You're using angular6+, so I suggest you to use reactive programming library such as rxjs



I made you a small example here.


[#51787] Thursday, August 1, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;