вы можете попробовать подписаться на фокус документа, а затем получить dateTime с сервера. После найдите разницу между датой клиента и значением. Например,
inc: number = 0;
timeInitial = 0;
time;
toogle: boolean = false;
constructor(private timerService: TimerService) {}
click() {
this.toogle = !this.toogle;
if (this.toogle) {
fromEvent(document, "focus")
.pipe(
takeWhile(() => this.toogle),
startWith(null),
switchMap(() => {
return this.timerService.getTime();
})
)
.subscribe(res => {
this.inc = new Date().getTime() - res.time;
if (!this.timeInitial) this.timeInitial = res.timeInitial;
console.log(this.inc, this.timeInitial);
});
timer(0, 1000)
.pipe(
takeWhile(() => this.toogle),
map(() => {
return (
this.timeInitial -
new Date(new Date().getTime() - this.inc).getTime()
);
})
)
.subscribe(res => {
this.time = res;
});
} else {
this.timeInitial = 0;
}
}
Ваш. html как
<button (click)="click()">{{toogle?'stop':'start'}}</button>
{{time |date:'H:mm:ss':'UTC'}}
И наш сервис, который делает вызов на сервер, который дайте нам дату и время, например,
export class TimerService {
constructor(private httpClient: HttpClient) {}
getTime() {
return this.httpClient
.get("https://worldtimeapi.org/api/timezone/America/Argentina/Salta")
.pipe(
map((res: any) => {
const time = new Date(res.datetime).getTime();
return {
time: time,
timeInitial: time + 30 * 60 * 1000
};
})
);
}
}
Ну, если вы измените время на своем компьютере, вы увидите, что изменение обратного отсчета, но когда вы сосредоточитесь на приложении, обратный отсчет обратного отсчета даст вам правильное время
Вы можете видеть в stackblitz