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
@Component({ selector: 'app-article-editor', templateUrl: './article-editor.component.html', })
Autosaving a form with RxJS in Angular
reactive-forms
rxjs-operators
debouncing
Advanced
8 steps
typescript
type QueuedRequest = { id: string; url: string; method: string;
A retry queue with exponential backoff
retry
exponential-backoff
persistence
Intermediate
10 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 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.