Я создал таймер, который не синхронизируется в нескольких браузерах. На неактивных вкладках браузеров или даже на устройствах таймер работает быстрее или медленнее.
На разных вкладках разница 3-4 секунды. Как их синхронизировать?
Это мой код модуля:
import { Observable, BehaviorSubject, Subscription } from 'rxjs';
export class RAFTimer {
public currentFrameId: number;
public startTime: number;
public numbers: BehaviorSubject<number>;
constructor() {
this._raf();
this.numbers = new BehaviorSubject<number>(0);
this.startTime = 0;
}
private _raf() {
this.currentFrameId = requestAnimationFrame(timestamp => this._nextFrame(timestamp));
}
private _nextFrame(timestamp: number) {
if ( this.startTime == 0) {
this.startTime = timestamp;
}
const diff: number = timestamp - this.startTime;
if ( diff > 100) {
const n: number = Math.round(diff / 100);
this.startTime = timestamp;
this.numbers.next(n);
}
this._raf();
}
cancel() {
cancelAnimationFrame(this.currentFrameId);
this.currentFrameId = null;
}
}
Это код компонента:
import { Component, Input, OnInit, OnDestroy } from '@angular/core';
import { RAFTimer } from './raftimer';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app';
public timeInterval:number=10;
public timeLeft:number=10000;
constructor(private timer:RAFTimer) {
}
ngOnInit() {
let countNumber=1;
let auctiontimer = this.timer.numbers.subscribe(
(val) => {
countNumber = countNumber+val;
if(countNumber >= this.timeInterval) {
this.timeLeft = this.timeLeft-countNumber/this.timeInterval;
if(this.timeLeft<0) {
this.timeLeft= 0;
}
countNumber=1;
}
});
}
}
Пожалуйста, запустите этот URL на двух разных вкладках вместе, и вы заметите разницу через несколько секунд или в течение 1 минуты.
https://angular -timer-raf.stackblitz.io /
Если вы хотите, вы можете также отредактировать эти строки кода, открыв этот URL ==>
URL https://stackblitz.com/edit/angular-timer-raf
Я также знаю, что когда браузер становится неактивным, таймер замедляется, я много раз искал, но у меня ничего не работает. Но мне нужно как-то синхронизировать таймер.