A user reported that the sale countdown jumped from 4:12 to 5:00 after they opened the popup. Nothing had restarted visibly. The worker had simply been replaced between two renders, and the replacement had no memory of the deadline.

The fix is one design decision: store the end of the countdown, never the amount left.

The short version

  • Persist endsAt (an absolute timestamp) and a label.
  • Render endsAt - Date.now() in every context that displays it.
  • Use alarms only to refresh the badge; use the popup's own interval for smooth updates.

The model

type Countdown = { id: string; label: string; endsAt: number; // epoch ms createdAt: number; }; 

Three fields do all the work. endsAt survives restarts, timezone changes and clock adjustments better than a remaining-seconds counter. createdAt lets you detect stale records after a schema change. label is what the user sees when the countdown is not active.

Store it in chrome.storage.local if the countdown must survive a browser restart — a flash sale does. Use session if it belongs to the current browsing session only.

Rendering in the popup

The popup is a normal DOM context. It can afford a one-second interval because it exists only while the user is looking at it.

let timer: number | undefined; async function mount() { const { countdown } = await chrome.storage.local.get('countdown'); if (!countdown) return; const tick = () => { const left = Math.max(0, countdown.endsAt - Date.now()); render(left); if (left === 0) { clearInterval(timer); void chrome.storage.local.remove('countdown'); } }; tick(); timer = setInterval(tick, 1000); window.addEventListener('unload', () => clearInterval(timer)); } 

The interval is a display loop, not the source of truth. If it is throttled or cleared, the next render recomputes the correct value from endsAt.

Rendering in the badge

The worker cannot hold a one-second interval, so the badge updates at alarm cadence. Thirty seconds is the practical floor.

async function refreshBadge() { const { countdown } = await chrome.storage.local.get('countdown'); if (!countdown) { await chrome.action.setBadgeText({ text: '' }); return; } const left = Math.max(0, countdown.endsAt - Date.now()); await chrome.action.setBadgeText({ text: formatShort(left) }); await chrome.action.setBadgeBackgroundColor({ color: left < 60_000 ? '#b3261e' : '#1a73e8' }); } async function startCountdown(label: string, durationMs: number) { const countdown: Countdown = { id: crypto.randomUUID(), label, endsAt: Date.now() + durationMs, createdAt: Date.now(), }; await chrome.storage.local.set({ countdown }); await chrome.alarms.create('countdown-refresh', { periodInMinutes: 0.5 }); await chrome.alarms.create('countdown-done', { when: countdown.endsAt }); await refreshBadge(); } chrome.alarms.onAlarm.addListener(async (alarm) => { if (alarm.name === 'countdown-refresh') await refreshBadge(); if (alarm.name === 'countdown-done') await completeCountdown(); }); 

The badge may lag by up to half a minute. That is acceptable for a toolbar indicator; it is not acceptable for a checkout screen, which is why the popup computes its own value.

The edge cases that actually bite

Expired while the browser was closed. On startup, load the record. If endsAt is in the past, show the expired state and clear it — do not restart the countdown from the full duration. This is the single most common bug in countdown implementations.

Clock changes. Date.now() follows the system clock. If the user changes their timezone, an absolute epoch still points at the same instant, which is what a sale deadline means. If the product means "24 hours of wall-clock time in the user's timezone", store a date string instead and document the difference.

Multiple tabs. Two popups can render the same countdown; both read from storage, so they agree. Do not keep a module-level cache in the popup without a storage listener, or one tab will show a stale value.

Paused countdowns. If the feature supports pause, store remainingMs at pause time and compute a new endsAt on resume. Never keep a paused countdown as a decrementing interval.

Why not just use setTimeout?

Because the countdown's whole value is that it keeps existing when nobody is watching. setTimeout stops at the worker boundary, and the remaining time is not recoverable from a dead callback. An alarm plus an end timestamp is the supported way to make the clock outlive the process.

If the countdown code is already entangled with other timers, vite-mv3-sw-compile-persist can rewrite long timer calls and persist top-level state at build time. It will not choose the deadline model for you, and it does not support destructured state or anonymous callbacks that close over locals — those still need a manual pass.

With and without the plugin

The before/after from the plugin's README is the whole argument:

Without vite-mv3-sw-compile-persist

let count = 0; chrome.action.onClicked.addListener(async () => { const stored = await chrome.storage.session.get('count'); count = (stored.count as number) ?? 0; count++; await chrome.storage.session.set({ count }); }); chrome.alarms.create('cleanup', { delayInMinutes: 5 }); chrome.alarms.onAlarm.addListener((alarm) => { if (alarm.name === 'cleanup') cleanup(); }); 

With vite-mv3-sw-compile-persist

let count = 0; chrome.action.onClicked.addListener(() => { count++; }); setTimeout(cleanup, 5 * 60_000); 

The second version is the code you meant to write. The plugin adds restore, dirty tracking, a debounced flush and alarm-backed timers at build time — no runtime import, no wrapper API.

Repository: vite-mv3-sw-compile-persist

If you are building a countdown this week, a star is a cheap way to keep the deadline-first examples coming.

Does your countdown end at a moment in time, or after a duration of use? The answer changes what you should persist.