What differenciates browser.alarms.create from setTimeout/setInterval in WebExtensions?
Asked Answered
A

3

8

I am creating a WebExtension for browsers. So I found out about the browser.alarms API. It basically allows you to set a (reoccurring or one-time) alarm and a callback will be fired.

Now, we've had such a feature this for a long time in JavaScript as in setTimeout and setInterval. So what is the difference to these ones? Why or in what cases may I prefer the one over the other?

I mean the main difference is obvious: You can only refire it e.g. in minutes, not seconds. Although, I think with when you can also unregister and re-register it in millisecond precision, but I think the API may be intended for longer periods, i.e. minutes. (I am just guessing here.) So why should I use it instead of a simple setInterval/setTimeout callback?

Alit answered 11/11, 2018 at 15:29 Comment(2)
Presumably alarms persist across browser sessions.Sorus
@Sorus I doubt so, as that would strictly go against most WebExtension APIs that loose their state when you e.g. update the add-on or restart the browser.Alit
D
11
  • setTimeout/setInterval time span is limited by 2^31-1 = 2147483647 i.e. ~24 days. Values less than 0 or bigger than that are cast into int32 range, which can produce unexpected results.

  • setTimeout/setInterval is part of standard DOM, not the isolated world, so when you use it inside a content script, the web page script can clear them accidentally via clearTimeout/clearInterval.
    Workaround: post a message to the background script so it sets the timer and sends a response upon finishing.

  • Event pages (those that have "persistent": false in manifest.json) won't wait for setTimeout / setInterval before unloading due to inactivity and won't wake up for such a timer so you can only use them for a very short time (currently the event pages are guaranteed to live for 5 seconds).

Within these designated limits you can safely use setTimeout/setInterval.

Depressor answered 11/11, 2018 at 16:27 Comment(0)
A
3

In addition to what has been posted, the alarm API seems to be more reliable:

  • if you setup alarm in the past, it will fire right away
  • if you setup future date and your PC wakes up from hibernation after the date, it will fire right after waking up
  • if you setup 8 hours from now, it will fire 8 hours from now (if your PC is on) no matter how long was your PC sleeping / hibernating in the meantime

See https://discourse.mozilla.org/t/how-reliable-are-alarms/40978/8?u=rugkx, thanks to Juraj Masiar from the Mozilla Community.

Alit answered 15/11, 2020 at 13:14 Comment(0)
P
2

To quote from the documentation on MDN:

This is like setTimeout() and setInterval(), except that those functions don't work with background pages that are loaded on demand.

Politburo answered 11/11, 2018 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.