I am setting a 60 seconds countdown with rxjs timer on Angular 11. It works fine when I keep that window open. But if I move away (click another tab of the same browser), the timer stops itself after several seconds. There's one time that I wait 3 minutes and get back and see there's 36 seconds left. How is that happening and is there a way to avoid that?
Related function on ts file:
countdown: number = 59;
countdownMapping: any = {
'=9' : '0#',
'=8' : '0#',
'=7' : '0#',
'=6' : '0#',
'=5' : '0#',
'=4' : '0#',
'=3' : '0#',
'=2' : '0#',
'=1' : '0#',
'=0' : '0#',
'other': '#'
};
resetResendTimer(clicked) {
if (this.countdownActive === false) {
this.countdownActive = true;
if (clicked) {
this.otherFunction();
}
// Trigger endCountdown after the countdown
timer(1000, 1000)
.pipe(
finalize(() => {
this.endCountdown();
}),
takeWhile(() => this.countdown > 0),
tap(() => this.countdown--)
)
.subscribe();
}
Related function on html file:
Resend verification code
<span *ngIf="countdownActive">
(0:{{countdown | i18nPlural: countdownMapping }})
</span>
CodePudding user response:
i've seen this behavior on Chrome and it's not related to RXJS, I think it's related to some restrictions applied on background tabs for more performance.
Every tab has a timer budget and this timer task is allowed to run only when the time budget is non-negative.
check more details here https://developers.google.com/web/updates/2017/03/background_tabs#budget-based_background_timer_throttling