I'm using chrome.alarm
to display countdown on extension icon, which updates every second'ish.
The problem I'm facing is if I change system's time forward (manually or if computer woke up from sleep), the counter starts racing, updating several times a second in attempt to catch up to new system time, or if I change time backwards, the timer stops.
How can I fix this so it would simply "jump" to current time?
Test extension:
manifest.json
{
"manifest_version": 3,
"name": "Test timer",
"author": "test",
"description": "Test chrome.alarm",
"version": "0.0.1",
"permissions":
[
"alarms"
],
"action": {},
"background": {
"service_worker": "service_worker.js"
}
}
service_worker.js
let i = 0,
start = new Date().getTime(),
pad = (n,s=2) => ("0"+n).slice(-s),
time = d => pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds()) + "." + pad(d.getMilliseconds(),3);
chrome.alarms.onAlarm.addListener(loop);
console.log("started");
loop();
function loop()
{
const now = new Date().getTime(),
//make sure timer doesn't drift from starting point
next = now - ((now - start) % 1000);
//repeat after 1sec
chrome.alarms.create({ when: next + 1000 });
chrome.action.setBadgeText({text:"" + (i = ++i % 1000)});
console.log("Date:", time(new Date(now)), "alarm:", time(new Date(next)));
}