Angular rxjs Observable.interval() not triggering properly on background tabs in Chrome
Asked Answered
G

1

7

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?

Groupie answered 27/7, 2017 at 12:48 Comment(0)
G
4

However, if setInterval() is used, there is no problem in any browser.

ngOnInit() {

  setInterval(()=>{

    console.log(new Date())
  },1000)  
}
Groupie answered 27/7, 2017 at 12:48 Comment(1)
sure this is a nice workaround but still no explanation why observables behave weird :DGantline

© 2022 - 2024 — McMap. All rights reserved.