我使用角拍卖网站,计算剩余时间从拍卖结束时间使用矩和显示计数器,但它失败时,用户改变他的时钟时间。
从服务器获得准确的时间并计算剩余时间是很好的,但是在页面加载后,干扰时钟会产生问题,是否有办法获取系统时钟更改事件或检查用户是否设置了自动同步/互联网时间?
在从服务器获得剩余时间的同时,还包括网络响应延迟和其他一些问题,需要知道向显示每个人完全相同的计时器的最佳方法。
发布于 2020-02-09 14:04:00
您可以尝试订阅文档焦点,然后获取服务器的dateTime表单。在找到客户端的日期与value.Some之间的不同之后,如
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中看到
https://stackoverflow.com/questions/60133699
复制相似问题