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
class DOMBatcher { constructor() { this.reads = []; this.writes = [];
Batching DOM reads and writes to avoid layout thrash
batching
requestanimationframe
layout-thrashing
Intermediate
8 steps
go
package web import ( "embed"
Serving embedded static assets in Go
embed
static-assets
http-handler
Intermediate
8 steps
javascript
export function buildPaginationUrl(baseUrl, { page, perPage, filters = {}, sort } = {}) { const url = new URL(baseUrl); const params = url.searchParams;
Building and parsing pagination URLs
url-parsing
query-string
pagination
Intermediate
8 steps
javascript
import { useSearchParams } from "react-router-dom"; const TABS = [ { id: "overview", label: "Overview" },
URL-driven tabs with React Router
url-state
query-params
accessibility
Intermediate
8 steps
javascript
const crypto = require('crypto'); function securityHeaders(options = {}) { const {
A configurable security-headers middleware in Express
middleware
http-headers
content-security-policy
Intermediate
7 steps
javascript
import { useRef, useCallback, useEffect, useState } from "react"; function useThrottle(callback, delay) { const lastRun = useRef(0);
Building a throttle hook in React
throttling
custom-hooks
refs
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.