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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A factory returning methods lets several functions share private state without exposing it.
  2. 2Guarding on a stored interval id makes start and stop idempotent and safe to call repeatedly.
  3. 3Optional-chaining callbacks keep the module useful even when no handlers are supplied.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a countdown timer with closures — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code