问题
I am writing angular2 application with interval timers implemented via RxJs observables, and just noticed the strange behaviour of Observable.interval() and Observable.timer() in Chrome browser when tab is in background. Angular component should once every second print number of seconds in console, but on background tabs, this is not working as intended - function triggers every x+1 seconds, where x is interval specified explicitely in the interval funciton
Angular component code:
ngOnInit() {
let a = Observable.interval(1000).subscribe(() => {
let date = new Date();
console.log(date.getSeconds());
});
}
Example: Console output on tab1 (tab with timer defined as above):
37 <- tab1 (with timer)
38
39
40
41 <- changed tab to tab2
43
45
47
49
51
53
55
57
59 <- changed tab to tab1
0
1
2
3
There is no problem with Mozzila FF.
I presume that this behaviour is consequence of lower priority of background tabs in browser, but why is the interval always postponed by just one second?
回答1:
However, if setInterval()
is used, there is no problem in any browser.
ngOnInit() {
setInterval(()=>{
console.log(new Date())
},1000)
}
来源:https://stackoverflow.com/questions/45351279/angular-rxjs-observable-interval-not-triggering-properly-on-background-tabs-in