Runny Yolk
Runny Yolk

Reputation: 1164

Angular 4 RXJS Observable .interval() Doesn't Work In Background

I have a simple timer observable which is subscribed to when a timer starts in my app. It works well, but if another browser tab is selected then the timer stops until the app's tab is selected again.

public timer = Observable
  .interval(100)

Is there a way I can keep the observable running while the tab is in the background?

Update

I looked briefly into running this as a Web Worker, but soon started reading about difficulties of integrating Web Workers into Angular projects.

So for the time being I'm using the simple solution of getting the start time of my timer and subtracting that from the current time to get the timer run duration. This way the timer will correct itself when when the tab becomes active again.

I did want the page title to display the timer count so that it can be seen just by looking at the tab, so I'd still like to find a better solution to this problem.

Upvotes: 5

Views: 6715

Answers (2)

Mark van Straten
Mark van Straten

Reputation: 9425

Tabs in the background of Chrome are heavily restricted in the amount of things performancewise they can do. See this blogpost of the Chrome team: https://developers.google.com/web/updates/2017/03/background_tabs

Shipping in Chrome 57, budget-based timer throttling is a further extension of the timer alignment mechanism, placing an additional limit on background timer CPU usage. It operates as follows:

  • Each background tab has a time budget (in seconds) for running timers in the background.
  • A page is subjected to time budget limitations after 10 seconds in the background.
  • A timer task is allowed to run only when the time budget is non-negative.
  • After a timer has executed, its run time is subtracted from the budget.
  • The budget continuously regenerates with time (currently set to a rate of 0.01 seconds per second). Note that this budget regeneration rate can be tweaked as Chrome collects more data about throttling behavior.

So running a timer ever 100msec in the background will not work dramatically slowed down due to the budget restriction in cpu cycles.

Upvotes: 5

Pranay Rana
Pranay Rana

Reputation: 176896

It doesnt seems like that , this is working

let j=0;
Rx.Observable.interval(1000).subscribe((v)=>{
  console.info('j: '+j++);})

Check here working demo : http://jsbin.com/zufebipawe/edit?html,js,console,output

also check here : https://github.com/ReactiveX/rxjs/issues/3042

Upvotes: 1

Related Questions