October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

Building a Timer That Survives Browser Crashes with Next.js and Supabase

Build a timer that recovers after reloads and crashes by storing deadlines instead of countdowns, saving on each action, and adding Supabase for cross-device recovery.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A timer survives a tab reload, a browser crash, or a restart when it stores its deadline instead of its countdown. The stored state is the source of truth. The on-screen number is recalculated from the current time each time the page loads or becomes visible again. A repeating JavaScript callback only refreshes the display. Browser storage (IndexedDB) covers recovery in the same browser profile. A Supabase record covers recovery for a signed-in user on other devices, or after local data has been cleared.

Why counting interval ticks breaks

The obvious approach is setInterval that subtracts one second per tick. It fails for two reasons. First, timers in hidden tabs are throttled, and some browsers slow them heavily after a tab has been in the background for a while, so the number of ticks no longer matches elapsed time. Second, any state held only in memory disappears when the tab closes. A countdown that is never written down cannot be recovered.

As an Amazon Associate I earn from qualifying purchases.

The fix is to record when the timer ends, not how much is left. Remaining time is then a subtraction performed whenever the UI needs it. Callback punctuality stops mattering.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Model the timer state

Persist the minimum state needed to reconstruct the timer. A workable shape is:

#1 Best Overall
Antonki 2 Pack Digital Timer for Kids Classroom Kitchen Timers for Cooking
  • 2‑PACK DIGITAL TIMER WITH BATTERY. This set includes 2 digital timers with 2 AAA batteries. It supports both count‑down and count‑up timing, max timing range up to 99 minutes 59 seconds. Built‑in memory function retains your last time setting without repeated reset, suitable for cooking, homework, focus study and workout timing. ( *It can not set Hour. Also no clock function. )
  • LOUD AUDIBLE ALARM & SILENT FLASHING RED LIGHT. 2 reminder modes for different environments. Loud beeping alarm can be heard from another room for kitchen cooking. Silent mode triggers flashing red light only, no beep noise, perfect for quiet classroom, kid's study room and library without disturbing others. ( *For alarm mode, timer will beep during setting. )
  • 3‑WAY MOUNTING OPTIONS. Each timer features magnetic back to attach on fridge or metal surface; fold‑out kickstand for desktop tabletop placement; hanging hole allows hanging (Need extra small string). 3 placement solutions fit kitchen, classroom, office and home desk scenarios. Small item size: 2.68"D x 2.48"W x 0.63"H. (You will get: 2 pcs digital timers, 2 pcs AAA batteries (Pre-install).
  • SIMPLE OPERATION & BATTERIES PRE‑INCLUDED. Easy M/S buttons make time setting intuitive for kids, seniors and teachers. 2‑pack AAA batteries are pre-included in timer, ready to use out of box. When not in use, please manually switch it to shut-off on the backside. ( *It does not feature auto shut off. Its battery can not be charged. )
  • WIDE‑APPLICATION HOUSEHOLD & CLASSROOM TIME MANAGEMENT TOOL. Practical timing tool for kitchen baking, egg boiling; classroom teaching for teachers; kids homework & screen‑time control; fitness exercise, hair salon timing and many more daily timing tasks. Perfect as homeschool supplies, classroom must haves, back to school supplies & teacher essentials. Compact lightweight design for home and travel use.
  • id: stable identifier for the timer.
  • status: idle, running, paused, or finished.
  • durationMs: the full length, used on reset.
  • deadline: epoch milliseconds when a running timer ends, or null.
  • remainingMs: the frozen remainder while paused, or null.
  • version and updatedAt: used for conflict detection when more than one writer exists.

Use Date.now() for anything persisted. performance.now() is relative to the page load and means nothing after a restart. Be aware that Date.now() follows the system clock, so a large clock change will shift a running timer. Show a note in the UI if that matters for your use case. The schema above is a design choice, not something the browser or framework dictates.

type TimerState = {
  id: string;
  status: 'idle' | 'running' | 'paused' | 'finished';
  durationMs: number;
  deadline: number | null;
  remainingMs: number | null;
  version: number;
  updatedAt: string;
};

export function remainingMs(t: TimerState, now = Date.now()): number {
  switch (t.status) {
    case 'running':
      return t.deadline === null ? t.durationMs : Math.max(0, t.deadline - now);
    case 'paused':
      return t.remainingMs ?? t.durationMs;
    case 'finished':
      return 0;
    default:
      return t.durationMs;
  }
}

Each control changes the state in one place:

  1. Start: set deadline = Date.now() + durationMs (or + remainingMs if resuming), set status = 'running'.
  2. Pause: set remainingMs = deadline - Date.now(), clear deadline, set status = 'paused'.
  3. Resume: set deadline = Date.now() + remainingMs, clear remainingMs, set status = 'running'.
  4. Reset: clear deadline and remainingMs, set status = 'idle'.
  5. Completion: when remainingMs(t) reaches zero while running, set status = 'finished'.

Each step increments version and sets updatedAt, then persists the result.

Save on each transition, not on unload

Write to storage when the user acts, not in a beforeunload or unload handler. MDN notes that during shutdown the browser may abort pending IndexedDB transactions, so a write started at that moment may never complete. The sequence below avoids relying on shutdown.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Antonki 2 Pack Digital Timer for Kids Classroom Kitchen Timers for Cooking
  • 2‑PACK DIGITAL TIMER WITH BATTERY. This set includes 2 digital timers with 2 AAA batteries. It supports both count‑down and count‑up timing, max timing range up to 99 minutes 59 seconds. Built‑in memory function retains your last time setting without repeated reset, suitable for cooking, homework, focus study and workout timing. ( *It can not set Hour. Also no clock function. )
  • LOUD AUDIBLE ALARM & SILENT FLASHING RED LIGHT. 2 reminder modes for different environments. Loud beeping alarm can be heard from another room for kitchen cooking. Silent mode triggers flashing red light only, no beep noise, perfect for quiet classroom, kid's study room and library without disturbing others. ( *For alarm mode, timer will beep during setting. )
  • 3‑WAY MOUNTING OPTIONS. Each timer features magnetic back to attach on fridge or metal surface; fold‑out kickstand for desktop tabletop placement; hanging hole allows hanging (Need extra small string). 3 placement solutions fit kitchen, classroom, office and home desk scenarios. Small item size: 2.68"D x 2.48"W x 0.63"H. (You will get: 1*Lime Green+ 1*Mint Green digital timers, 2 pcs AAA batteries (Pre-install).
  • SIMPLE OPERATION & BATTERIES PRE‑INCLUDED. Easy M/S buttons make time setting intuitive for kids, seniors and teachers. 2‑pack AAA batteries are pre-included in timer, ready to use out of box. When not in use, please manually switch it to shut-off on the backside. ( *It does not feature auto shut off. Its battery can not be charged. )
  • WIDE‑APPLICATION HOUSEHOLD & CLASSROOM TIME MANAGEMENT TOOL. Practical timing tool for kitchen baking, egg boiling; classroom teaching for teachers; kids homework & screen‑time control; fitness exercise, hair salon timing and many more daily timing tasks. Perfect as homeschool supplies, classroom must haves, back to school supplies & teacher essentials. Compact lightweight design for home and travel use.
  1. On every transition, open a readwrite transaction on the timer store and put the new state.
  2. Treat the save as complete only after the transaction’s complete event fires. If you show a saving indicator, clear it at that point.
  3. Run a short interval, around 250 ms to 1000 ms, that only re-renders remainingMs(state). It does not write to storage.
  4. Listen for visibilitychange on document. When document.visibilityState becomes visible, reload the stored state and recompute the display immediately. Do not assume callbacks ran while the page was hidden.
  5. On startup, load the latest record. If the saved status is running and the deadline has passed, move the state to finished and persist that change.

The visibility listener is a refresh trigger, not a timer. It tells you when to re-read the state.

What local recovery can and cannot promise

IndexedDB is an asynchronous, browser-local store. It is well suited to saving timer records, and a single transaction can cover related changes so they are saved together or not at all. It is scoped to one browser origin on one profile, so it does not follow the user to another device.

Browser storage is best-effort by default. The user can clear site data, the browser can evict data under storage pressure, and private browsing sessions can discard data when they end. navigator.storage.persist() asks the browser to treat the origin’s storage as persistent, where supported. It is a request, not a guarantee, and it does not protect against deliberate deletion. Check the returned boolean and show a clear message to users when the request is denied. Describe local recovery to them as “best-effort on this browser,” not as permanent storage.

Rank #3
Elegant Digital Kitchen Timer Stainless Steel - Loud Alarm - Model eT-23
  • “Great Little Timer” 2026 Model: Elegant Digital Kitchen Timer Stainless Steel - Strong Magnetic Back - Kickstand - Loud Alarm - Large Display - Auto Memory - Auto Shut-Off - Model eT-23 by eTradewinds. We eliminated the annoying little button beeps every time buttons are pressed. New lanyard attachment feature for hanging timer around neck belt or wrist. Adjustable angle fold-out countertop kickstand. Counts up/down 99 min/59 sec w/ Auto-Memory for repeated tasks. Auto-Memory holds previous setting for the next event. Want 3 min eggs every morning? Set time once and only press start every morning. 3 min. will stay in memory until reset & new time is entered.
  • Simplified Operation: Press 2 left buttons simultaneously for a reset to 0000. Press & hold Min. or Sec. buttons for 2 sec. to fast forward your numbers. Just press and hold. Can also be paused and restarted to count up/down incrementally if you wish. Large, Bright, Easy-To-Read LCD Display: Can effortlessly be seen from across the room. Pleasant, loud, mellow 80dB+ beep can easily be heard in other rooms & will sound for 62 seconds, or can be shut-off manually.
  • Strongest Timer Magnet Listed Anywhere: Powerful Neodymium earth magnet & anti-scratch appliance saver foam. Our timers won't slide down your fridge or scratch appliances. Anti-Wobble Stabilizing Anchor Points: Designed on all 4 corners eliminating wobble, pivot, or movement when buttons are pressed while magnet secured. What good is a timer you can’t use while attached? This timer won't pop off your range hood and backflip into your boiling soup because you hit the off button. "No soup fer yu"
  • Convenient Battery Saving Auto Shut-Off Feature: Engages when magnetic timer is idle and not being used for 3 minutes. Pressing any button will turn these durable kitchen timers for cooking on. (1) AAA Battery included. A Favorite: medical, dental, therapy, & productivity timer. Perfect cute egg timer for boiling eggs, kitchen timer, 2nd oven timer, cooking timer, kids timer, study timer, classroom timer, workout timer, visual timer, & are nice loud kitchen timers for seniors.
  • USA-Based Company: Buy with confidence. We believe 100% in the quality of our timers. If it should EVER fail to function properly in residential use due to component failure (Excluding Battery), we will replace it free and pay for shipping in the USA. No expired time limits. Just contact us via Amazon or use our included email or phone number, and our cheerful support team will quickly respond. This is the last digital timer you will ever need to buy, promise.

Keep browser APIs in Client Components

In the Next.js App Router, components are Server Components unless marked otherwise. The Next.js documentation summarises the boundary as: “The client and server environments have different capabilities.” Storage, visibility listeners, and timers therefore belong in a Client Component.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Put 'use client' at the top of the timer component file, and render it from a Server Component page.
  • Do not read window, document, or IndexedDB during render. Read them inside useEffect.
  • Keep the server-rendered and first client render identical. Until the stored state has loaded, render a neutral state such as “Restoring timer…”. Do not render a guessed countdown, because the saved value will replace it and cause a visible jump.

Hydration is the step where React attaches event handlers to HTML the server already produced. If the first client render disagrees with that HTML, React reports a mismatch, which is why the loading state matters.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Add Supabase for cross-device recovery

A Supabase record is worth adding when the timer must follow a signed-in user across browsers or devices, or survive clearing local storage. Local storage and a Postgres database do not synchronise by themselves. Your application must write to both or decide which one is authoritative.

Rank #4
Sale
Digital Magnetic Kitchen Timer & Stopwatch with LED Display, Space Gray
  • Smooth Twist Control – Responsive & Frustration-Free – This digital kitchen timer features a refined rotary system for smooth and precise control. No lag or repeated pressing—just twist to set instantly. Counting down from 99 minutes 55 seconds to zero, or as a stopwatch count up from 0 to 99:55. A reliable kitchen timer for cooking, study timer, and timer for classroom, perfect for seniors and kids
  • ECO Brightness Level for Extended Battery Life - It would automatically enter power saving mode 5s after paused/stop, just press the button on the screen to activate it again as you need. A 3-inch large digital timer screen ensures excellent visibility across the room. Whether baking or cooking, this cooking timer helps prevent overcooking and keeps your tasks perfectly on time
  • Loud, Soft & Mute Modes – Built for Every Environment – This versatile countdown timer offers three adjustable sound levels: Loud (80-90dB), Soft (60-75dB) and Silent to match your needs. Use it as a productivity timer, desk timer, or classroom timer, ensuring clear alerts in busy kitchens or quiet spaces without disturbance
  • Strong Magnetic Back – Stable & Hands-Free Use – Built as a powerful magnetic timer, it attaches firmly to fridges, ovens, or boards. The anti-slip design ensures stability, allowing one-hand operation without removing this magnetic kitchen timer, ideal for multitasking while cooking
  • Durable Design – Made for Everyday Use – Crafted from high-quality ABS, this digital timer is built for long-term reliability. Compact and modern, it’s not only a dependable kitchen timer manual alternative but also a thoughtful gift for families, students, and professionals

A practical pattern is to keep IndexedDB as the fast local copy and treat the Supabase row as the copy shared between devices. On load, compare version or updatedAt from both and keep the newer state. When the device is offline, keep working from the local copy and queue the update.

Table and policy

create table public.timers (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  status text not null check (status in ('idle','running','paused','finished')),
  duration_ms bigint not null,
  deadline_ms bigint,
  remaining_ms bigint,
  version integer not null default 1,
  updated_at timestamptz not null default now()
);

alter table public.timers enable row level security;

create policy "Users manage their own timers"
on public.timers
for all
to authenticated
using (auth.uid() = user_id)
with check (auth.uid() = user_id);

Conflict handling

If the same timer can be edited from several tabs or devices, use optimistic concurrency. Send the version you last read, and let the database accept the write only if that version is still current:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const { data, error } = await supabase
  .from('timers')
  .update({
    status: next.status,
    deadline_ms: next.deadline,
    remaining_ms: next.remainingMs,
    version: current.version + 1,
    updated_at: new Date().toISOString(),
  })
  .eq('id', current.id)
  .eq('version', current.version)
  .select();

An empty data array with no error means another writer changed the row first. Reload the row, reconcile, and retry. For a single-user, single-device timer, last-write-wins may be enough. Collaborative or shared timers need a stronger rule, and the policy should be written down before launch because Supabase does not define one for timers.

Best Value
AOUCE Digital Kitchen Timers for Cooking, Timer for Kids 2 Pack White
  • Kitchen Timers with big buttons, large digital display, loud buzzer and clean bright look(Battery Not Included)
  • Clear and Loud alarm, you will easily be able to hear this alarm in another room, and the alarm will stop auto after 30seconds when you in busy
  • Cooking timer with Strong Magnetic back 2.0 retractable stand and hook for hanging, can be positioned in variety of locations, like table, refrigerator, dry erase board and wall hooks
  • Maximum time is 99 minutes 59 seconds, meet the need of home perfectly. You can save the battery with ON/OFF switch
  • Memory Setting: You do not need to set the countsown time every time, it will remeber your last time and you only need to press "ST/SP" button

Browser and server clients

Create the browser client with the project URL and the publishable key, and use it only for operations that RLS allows. Server-rendered authenticated pages should use Supabase’s Next.js SSR guidance, which relies on cookie-based sessions and separate browser and server clients. Do not accept a user identifier from the request body and trust it for authorisation. Derive the user from the verified session.

Security boundaries

  • Enable RLS on every table exposed through the Data API, and grant each role only the operations it needs.
  • The publishable key is designed for browser code, but only when RLS policies are correct.
  • A secret or service-role key bypasses RLS. Keep it in server-only environment variables and never prefix it with NEXT_PUBLIC_.
  • Test policies by signing in as two different users and confirming that each can read and modify only their own timers.

Local-only or server-backed

Concern IndexedDB only IndexedDB plus Supabase
Recovery scope One browser profile on one device Signed-in user across devices
Works offline Yes, reads and writes locally Local reads and writes yes; remote sync needs a connection
Loss if site data is cleared Timer state is lost Server copy remains, if the account is accessible
Account required No Yes, with authentication
Build effort Storage schema and transitions Adds auth, RLS policies, sync, and conflict handling

Choose local-only when the timer is an anonymous, single-device tool. Add Supabase when losing the timer would matter to the user, or when they expect to see it on another device.

Failure cases and checks

  • Tab reloaded while running: the stored deadline is read and the remaining time is recalculated. No duplicate countdown should start.
  • Browser crashed mid-save: the last transition whose transaction completed is restored. Test this by killing the browser during a save and confirming the previous state, not a corrupted one, is loaded.
  • Laptop asleep past the deadline: on wake, the state is finished. A completion notification or sound should play only once; store a notifiedAt value to prevent repeats.
  • Site data cleared: local state is gone. Recovery depends on whether a server copy exists.
  • Two tabs editing one timer: with versioned writes, one update succeeds and the other reloads. Without them, the later write silently overwrites the earlier one.

Browser and vendor behaviour changes over time. Check the current MDN, Next.js, and Supabase documentation for the browsers and versions you target before shipping.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Bottom Line

Store the deadline and the frozen remainder, not a running count. Persist on each user action, recalculate on load and on visibility change, keep storage code inside a Client Component, and add Supabase with RLS and versioned writes only when recovery must cross devices or survive cleared local storage.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.