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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing an absolute deadline instead of a remaining duration lets a timer resume accurately after interruptions.
  2. 2Guarding start/stop against a live interval id keeps timer lifecycle idempotent and leak-free.
  3. 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.

A countdown timer that survives reloads — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code