typescript
52 lines · 10 steps
A countdown timer that survives reloads
A TypeScript class persists its deadline to localStorage so a countdown resumes correctly across page reloads.
Explained by
highlit
1type CountdownState = {
2 deadline: number;
3 onTick: (remaining: number) => void;
4 onComplete: () => void;
5};
6
7const STORAGE_KEY = "countdown:deadline";
8
9export class PersistentCountdown {
10 private intervalId: number | null = null;
11 private deadline: number;
12
13 constructor(private readonly config: Omit<CountdownState, "deadline"> & { durationMs: number }) {
14 const stored = localStorage.getItem(STORAGE_KEY);
15 const restored = stored ? Number(stored) : NaN;
16
17 this.deadline = Number.isFinite(restored) && restored > Date.now()
18 ? restored
19 : Date.now() + config.durationMs;
20
21 localStorage.setItem(STORAGE_KEY, String(this.deadline));
22 }
23
24 start(): void {
25 if (this.intervalId !== null) return;
26 this.tick();
27 this.intervalId = window.setInterval(() => this.tick(), 1000);
28 }
29
30 stop(): void {
31 if (this.intervalId !== null) {
32 window.clearInterval(this.intervalId);
33 this.intervalId = null;
34 }
35 }
36
37 reset(durationMs: number): void {
38 this.deadline = Date.now() + durationMs;
39 localStorage.setItem(STORAGE_KEY, String(this.deadline));
40 }
41
42 private tick(): void {
43 const remaining = Math.max(0, this.deadline - Date.now());
44 this.config.onTick(remaining);
45
46 if (remaining <= 0) {
47 this.stop();
48 localStorage.removeItem(STORAGE_KEY);
49 this.config.onComplete();
50 }
51 }
52}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing an absolute deadline instead of a remaining duration lets a timer resume accurately after interruptions.
- 2Guarding start/stop against a live interval id keeps timer lifecycle idempotent and leak-free.
- 3Validating restored persisted values before trusting them avoids resuming from stale or corrupt state.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-countdown-timer-that-survives-reloads-explained-typescript-290f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.