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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 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
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
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/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.