javascript
45 lines · 9 steps
Building a countdown timer with closures
A factory function keeps timer state private and exposes start, stop, and reset controls.
Explained by
highlit
1function createCountdownTimer(durationSeconds, { onTick, onComplete } = {}) {
2 let remaining = durationSeconds;
3 let intervalId = null;
4
5 const format = (total) => {
6 const minutes = String(Math.floor(total / 60)).padStart(2, "0");
7 const seconds = String(total % 60).padStart(2, "0");
8 return `${minutes}:${seconds}`;
9 };
10
11 const stop = () => {
12 if (intervalId !== null) {
13 clearInterval(intervalId);
14 intervalId = null;
15 }
16 };
17
18 const start = () => {
19 if (intervalId !== null) return;
20
21 onTick?.(remaining, format(remaining));
22
23 intervalId = setInterval(() => {
24 remaining -= 1;
25
26 if (remaining <= 0) {
27 remaining = 0;
28 onTick?.(remaining, format(remaining));
29 stop();
30 onComplete?.();
31 return;
32 }
33
34 onTick?.(remaining, format(remaining));
35 }, 1000);
36 };
37
38 const reset = (newDuration = durationSeconds) => {
39 stop();
40 remaining = newDuration;
41 onTick?.(remaining, format(remaining));
42 };
43
44 return { start, stop, reset };
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A factory returning methods lets several functions share private state without exposing it.
- 2Guarding on a stored interval id makes start and stop idempotent and safe to call repeatedly.
- 3Optional-chaining callbacks keep the module useful even when no handlers are supplied.
Related explainers
javascript
import { useReducer, useCallback } from 'react'; function historyReducer(state, action) { const { past, present, future } = state;
Undo/redo form state with a React reducer
undo-redo
reducer
immutability
Intermediate
10 steps
javascript
import { NextResponse } from 'next/server'; import { db } from '@/lib/db'; function csvCell(value) {
Streaming a CSV export in a Next.js route
streaming
csv
readablestream
Advanced
9 steps
typescript
type Countdown = { days: number; hours: number; minutes: number;
Building a self-stopping countdown timer
date-math
closures
timers
Intermediate
9 steps
javascript
class MovingAverage { constructor(windowSize) { if (!Number.isInteger(windowSize) || windowSize <= 0) { throw new RangeError('windowSize must be a positive integer');
A rolling average over a fixed window
circular-buffer
streaming
async-generators
Intermediate
7 steps
rust
use rand::distributions::{Alphanumeric, DistString}; use rand::rngs::OsRng; #[derive(Debug, Clone, PartialEq, Eq)]
A newtype wrapper for API tokens in Rust
newtype-pattern
randomness
encapsulation
Intermediate
6 steps
php
<?php namespace App\Validation;
Building a reusable address form validator in PHP
validation
error-accumulation
regex
Intermediate
9 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/building-a-countdown-timer-with-closures-explained-javascript-9c7a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.