-1

I have been working on a html-website lately. The website is a web-app made to measure time spent on a project and to map your efficiency per hour of the day.

I have tested this website while looking at the website, and it worked fine. It is that I have just recently added a part where it will map your time over the day, and since I had to wait for 5 minutes while the clock was passing a 5 minute treshhold, I figured that it would be efficient to do some other things while letting the clock do its thing.

Unfortunately I was kind of shocked to see that the clock had not changed even a millisecond, and that has to be because the js-interval was not continued when viewing a different chrome tab. Once I opened the clock it continued where it was left once I switched tabs.

Now my question is: Is there a way to let the HTML-website run in the background, just like a background-application, so you can do other tasks while the website will continue it's interval?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Bjorn
  • 83
  • 1
  • 10
  • This may help: https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome – Riddell Sep 04 '19 at 19:50

1 Answers1

0

Chrome manages to save resources from tabs which are in background, so when you call setTimeout or setInterval - it still runs but not more than 1 call in a second. So if your code tried to call setTimeout 1,000,000 times, you will wait next 1,000,000 seconds until all calls will be completed. And sometimes you don't realize, that some animation calls setTimeout many-many times for many animated objects :-)

The way of implementing what you need - is to abstract from timeouts and calculate time difference from last call.

Example:


  let lastMesure = Date.now();
  let workTime = 0;

  setInterval(() => {
    const now = Date.now();
    workTime += (now - lastMeasure);
    lastMeasure = now;
  }, anyTimePeriod);

It will sleep most of the time when tab is in background, but when you switch back to the tab - first calculation will get you back to right value.

Oleg Imanilov
  • 2,591
  • 1
  • 13
  • 26