2

This is my first chrome extension using manifest v3, and I want to make a timer in it.

This is supposed to update every second, and not run on any specific tab nor the popup window.

I tried to do this in my service worker:

let counter = 0
setInterval(() => {
    counter++
}, 1000)

But that didn't work well, because after around half a minute, the service worker would go "inactive", and thus stop this loop.

So I am just looking for a way to make a loop that executes some code every 1 second. This loop always has to be running. And I do not really have a way to "launch" say a function every second from another page. I can start it once, but because of the service worker that goes inactive after a while, then this script has to either just never die or relaunch itself every second.

Is this even possible?

Tobias H.
  • 426
  • 1
  • 6
  • 18
  • 1
    Depending on how you use this counter there may be a solution but generally MV3 doesn't have one. The only workarounds are listed here: [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm Dec 30 '21 at 20:00

1 Answers1

0

Google recommends using their "Alarm API" instead of timers to schedule running code: https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/#alarms

So instead of running a "setTimeout" or "setInterval" in your background worker like this:

const TIMEOUT = 3 * 60 * 1000; // 3 minutes in milliseconds
setTimeout(() => {
  chrome.action.setIcon({
    path: getRandomIconPath(),
  });
}, TIMEOUT);

You should instruct Chrome on when to run it instead:

chrome.alarms.create({ delayInMinutes: 3 });

chrome.alarms.onAlarm.addListener(() => {
  chrome.action.setIcon({
    path: getRandomIconPath(),
  });
});
Jack Dunsk
  • 91
  • 1
  • 11
  • Not super helpful, as the question was about firing alarms every second. The Alarms API limits the interval alarms can be fired at: `Alarm period is less than minimum of 1 minutes. In released .crx, alarm "myAlarm" will fire approximately every 1 minutes.` – Marv Sep 30 '22 at 08:28