Inactive tab setinterval behaviour

I am working on pomodoro project. I am using setinterval to call the animating function with 1000 interval.
`window.setInterval(func, 1000);
I want to know how is this approach reliable?
My major concern is - will it work properly in inactive tab?

Currently I tested in firefox and chrome- all works fine.
But what about others?


PS. Before that I was playing with settimeout with less than 1000ms(say with value 10). On inactive tabs interval was changing to 1000 and I didn’t expect that.

`

1sec works fine in inactive tabs. Per spec, timers are clamped to 1000ms in inactive tabs.

MDN source

1 Like

Thank you. That what I was looking for. The repaired link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Timeouts_in_inactive_tabs_clamped_to_>1000ms

1 Like

You can use page visibility API to help you work with the intervals that are shorter than 1000ms.
Here’s the documentation:
https://www.w3.org/TR/page-visibility/
and an info page with an example:
https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

1 Like

something I have never heard before.
Update.
Thank you. One more topic to learn more about.
But how can I approach my problem with this api?

Are you sure? I think the tab loses access to shorter timers as soon as visibility is lost. I don’t see anything about timers under 1 second in either of those pages. Do you have an example of working with timers shorter than 1000ms using page visibility?

You can use the api to set an event listener to register a change in page visibility.
Start the interval by checking if the page is visible. Write two different codes for each possibility.
Say you set the interval to 100.
If page is visible, advance the timer every 10th iteration, but do the illustration each time you pass through.
If page in invisible (interval is now changed to 1000) advance the timer every time, but move the illustration 10 steps further to make up for the missed steps.

2 Likes

Aaaaaaaah… ! :thumbsup:

Yes, I used this in my own timer. Here’s the finished timer: https://beekey.github.io/timer/. Here’s the js part of the code: https://github.com/Beekey/timer/blob/master/js/index.js

1 Like

Very elegant solution. I like it

1 Like

Thank you very much)
But I noticed a strange thing. If I open html page with my stopwatch directly - setInterval slows down when tab becomes insctive. If I open html page by link on another page - most of the time stopwatch doesn’t slow down when inactive. In last case workaround with document.hidden doesn’t help much - my stopwatch runs 100x faster than needed)