Alarms and setTimeout & setInterval in background scripts

(Gary) #1

I’m a little confused by the MDN documentation concerning Alarms and the use of setTimeout and setInterval in background scripts.

Where it reads, in referring to setTimeout and setInterval, that “…those functions don’t work with background pages that are loaded on demand”, does it mean they won’t work in the background script period?

What I am looking to do is maintain a timer to administer a set of timed activities and I don’t want the timer to pause if the tab is minimized, as happens when these functions are run in the JS of a normal page. I could set the activity to terminate if the tab is minimized but, if possible, I’d like to give the option to leave the tab and keep the timer running, such that if the time expires before returning to the page, upon return there would still be displayed a message that the time had expired.

Also, two timers are required: one that is an overall timer for the whole set of activities and one that resets for each individual activity. I have it working in the JS of a normal page but both timers pause when the tab is left and resume upon return. Of course, I need to display the ticking-down time in the page, not just keep track of it in the background. By “left” I mean the user just moves to another tab or minimizes the browser and keeps the page loaded.

At first read, I thought the Alarms API would handle this, but according to the alarms.create() documentation, it appears that the time intervals must be full minutes and I need seconds.

Is there a realiable way to accomplish this in Firefox only?

Thank you.

(Martin Giger) #2

setTimeout and setInterval will work just fine in Firefox. That part of the documentation refers to “event” background pages, which chrome would like to be the default, while in Firefox background pages are by default “persistent”, so always loaded.

The accuracy of alarms may be higher, from what I understand. However they are intended for larger spans of time. If you need very quick intervals or timers, use setTimeout/setInterval.

(Gary) #3

Thank you for responding to my question. Do you know if the extension setTimeout and setInterval will continue to run when the browser is minimized? I will find out soon anyway but wondered if extension code will pause like the the individual page code does when the browser is minimized or the tab is not the active tab.

Thank you.

(Martin Giger) #4

The timeouts/intervals in the background page will continue to run normally, not sure about content scripts.