简体   繁体   中英

Observable timer ticks slows down with time

I am using the observable timers to calculate the time left for an auction and don't want to depend on the client side time. So, I make a service call to our API which returns the localized time and then I create the observable timer which is called after each 1 second where I could add 1 second to the server time to replicate the current server time on client end.

The issue is, after each 15 minutes, there is a gap of around 6 seconds between what the server time is and what our timer is giving. In an hour, the difference increases to around 40 seconds and it continues to increase as long as we don't refresh or reopen the page.

I know that sounds silly but the observable timer which is being called after 1 second interval is slowing down a little (3 seconds in each 10 minutes or so).

Here's the code I am using:

//get the server date
this.service.getServerTime().subscribe(serverDate => {
    this.serverDate = serverDate;
}, error => { });

To start the timer, I am using

//start the timer using observable
let timer = Observable.timer(1000, 1000);
this.timerSubscription = timer.subscribe((t: any) => {
    this.timerExecuted();
});

private timerExecuted(): void {
    if (!this.serverDate) {
        return;
    }       
    //add 1 second to the server date
    this.serverDate.setSeconds(this.serverDate.getSeconds() + 1);

    //console log the server date after adding 1 second
    console.log(this.serverDate);
}

When I check the console.log(this.serverDate) , initially it starts with the correct date. Assume the time was: 07:15:00PM , after exactly an hour, the time logged will be 08:14:20PM . After exact 24 hours, strangely enough, the time logged is around 06:45PM which is way off target.

The main target is to get the server time running on client in real time without having to depend on the user's local clock. I get the current time from server when the user lands in angular, start the timer using observable (1 second interval) and add seconds in the server time that I received. The ticks I receive from observable significantly slows down over the period of few minutes.

We noticed that at some point the intervals increased 4x. Turns out that some browsers throttle timers to only fire once per second when out of focus (inactive tab) to save battery.

Some additional information can be found here , here or here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM