Digital clock (HH:MM:SS) with setInterval in JavaScript
Advanced · 4 min read
A digital clock on a web page is a nice small project: every second, show the time as HH:MM:SS, like 14:37:42. The same pattern drives countdown timers, quiz timers and "last updated" labels.
In this tutorial you will build the clock in two parts. First, a function that turns a number of seconds into HH:MM:SS. Second, a function that calls it once a second. You will also learn a neat trick: passing the timer in as an argument, so you can test the clock without waiting. You need to know functions, arrow functions and %, the remainder operator.
setInterval in one minute
setInterval(fn, ms) runs fn again and again, every ms milliseconds. 1000 milliseconds is one second. It returns a handle, and clearInterval(handle) stops it.
In a browser, the whole clock can be one line:
setInterval(() => console.log(new Date().toTimeString().slice(0, 8)), 1000);
toTimeString() starts with the time, like 14:37:42 GMT+0100 ..., and slice(0, 8) keeps the first eight characters. That line prints forever, though, and nobody can check its output without sitting and watching. So the answer splits the job into pieces it can test.
Seconds since midnight
A time of day can be stored as one number: seconds since midnight. 14:37:42 is 14 hours, 37 minutes and 42 seconds, which is 14 * 3600 + 37 * 60 + 42, or 52662 seconds.
Here is the exercise. Try it yourself first if you like, then read on and we will build it.
8 A clock that ticks every second
hardPrint the time as HH:MM:SS once a second. Build it so the ticking can be tested without waiting.
Stuck? Three hints, smallest first
- 1.
padStart(2, ‘0’)is what turns9into09. - 2. Take the timer and the clock as arguments instead of reaching for the globals.
- 3. A test can then drive time forward instantly, and the same code still works in a browser.
Step 1: pad to two digits
A clock shows 09, not 9. padStart(2, '0') adds zeros at the front until the text is two characters long:
const two = (n) => String(n).padStart(2, '0');
console.log(two(9)); // 09
console.log(two(42)); // 42
padStart is a string method, so the number is turned into a string first with String(n).
Step 2: split seconds into hours, minutes and seconds
Math.floor rounds down. Dividing by 3600 gives whole hours. Dividing by 60 gives whole minutes, and % 60 keeps only the minutes past the hour. % 60 on the total gives the seconds left over:
const formatTime = (s) =>
[Math.floor(s / 3600), Math.floor(s / 60) % 60, s % 60].map(two).join(':');
console.log(formatTime(52662)); // 14:37:42
console.log(formatTime(9 * 3600 + 5 * 60 + 3)); // 09:05:03
map(two) pads each of the three numbers, and join(':') puts the colons between them.
Step 3: the midnight bug
What happens one second after 23:59:59?
console.log(formatTime(86399)); // 23:59:59
console.log(formatTime(86400)); // 24:00:00
There are 86400 seconds in a day, so second 86400 is midnight again. A clock should show 00:00:00. The fix is to wrap with % 86400. The answer writes it as ((totalSeconds % 86400) + 86400) % 86400, which also turns a negative number into a sensible time:
const formatTimeWrapped = (totalSeconds) => {
const s = ((totalSeconds % 86400) + 86400) % 86400;
return [Math.floor(s / 3600), Math.floor(s / 60) % 60, s % 60].map(two).join(':');
};
console.log(formatTimeWrapped(86400)); // 00:00:00
console.log(formatTimeWrapped(86400 + 61)); // 00:01:01
console.log(formatTimeWrapped(-1)); // 23:59:59
In the answer this wrapped version is the one called formatTime.
Step 4: take the timer as an argument
Here is the trick. Instead of calling the global setInterval and reading the real time inside the function, startClock receives a clock object that provides both:
function startClock(clock, onTick) {
const handle = clock.setInterval(() => onTick(formatTimeWrapped(clock.now())), 1000);
return () => clock.clearInterval(handle);
}
Every second it reads clock.now(), formats it and hands the text to onTick. It returns a small function that stops the clock. This style is called dependency injection: the function is given what it depends on, instead of reaching out for it.
Step 5: a fake clock you can fast-forward
Because startClock only uses now, setInterval and clearInterval, anything with those three can stand in for real time. The answer's makeClock keeps a pretend "now" in seconds and a list of jobs, and adds an advance(seconds) method that moves time forward and runs every job that falls due. Its core is short:
function makeClock(startSeconds = 0) {
let now = startSeconds;
let jobs = [];
return {
now: () => now,
setInterval(fn, ms) {
const job = { fn, ms, next: now + ms / 1000 };
jobs.push(job);
return job;
},
clearInterval(job) { jobs = jobs.filter((j) => j !== job); },
advance(seconds) {
const target = now + seconds;
while (true) {
const due = jobs.filter((j) => j.next <= target).sort((a, b) => a.next - b.next)[0];
if (!due) break;
now = due.next;
due.next += due.ms / 1000;
due.fn();
}
now = target;
},
};
}
advance keeps picking the earliest job that is due before the target time, moves now to that moment, schedules the job's next run and calls it.
Step 6: run six seconds instantly
const clock = makeClock(14 * 3600 + 37 * 60 + 42);
const ticks = [];
const stop = startClock(clock, (t) => ticks.push(t));
clock.advance(6);
stop();
clock.advance(10);
console.log(ticks.join(' ')); // 14:37:43 14:37:44 14:37:45 14:37:46 14:37:47 14:37:48
console.log(ticks.length); // 6
Six pretend seconds gave six ticks, with no real waiting. After stop(), ten more seconds add nothing. In a browser you would pass a real clock instead: { now: ..., setInterval, clearInterval } built on Date and the global timer functions.
The full solution
The panel holds the fake clock, the formatting, startClock, and the one-line browser version as a comment. It fast-forwards six seconds and prints each tick. Press Run to see them.
// ---- the stand-in ----------------------------------------------------------
// The build has no second to wait, so time is injected. makeClock is the fake;
// the real setInterval and Date are what you would pass in a browser.
function makeClock(startSeconds = 0) {
let now = startSeconds;
let jobs = [];
return {
now: () => now,
setInterval(fn, ms) {
const job = { fn, ms, next: now + ms / 1000 };
jobs.push(job);
return job;
},
clearInterval(job) { jobs = jobs.filter((j) => j !== job); },
// Drive time forward and fire whatever is due.
advance(seconds) {
const target = now + seconds;
while (true) {
const due = jobs.filter((j) => j.next <= target).sort((a, b) => a.next - b.next)[0];
if (!due) break;
now = due.next;
due.next += due.ms / 1000;
due.fn();
}
now = target;
},
};
}
// ---- the answer ------------------------------------------------------------
const two = (n) => String(n).padStart(2, '0');
const formatTime = (totalSeconds) => {
const s = ((totalSeconds % 86400) + 86400) % 86400; // wrap at midnight
return [Math.floor(s / 3600), Math.floor(s / 60) % 60, s % 60].map(two).join(':');
};
function startClock(clock, onTick) {
const handle = clock.setInterval(() => onTick(formatTime(clock.now())), 1000);
return () => clock.clearInterval(handle);
}
// In a browser this line is the whole thing:
// setInterval(() => console.log(new Date().toTimeString().slice(0, 8)), 1000);
// 14:37:42 is 52662 seconds past midnight, matching the sample output.
const clock = makeClock(14 * 3600 + 37 * 60 + 42);
const ticks = [];
const stop = startClock(clock, (t) => ticks.push(t));
clock.advance(6); // six seconds, instantly
stop();
clock.advance(10); // nothing more should arrive
for (const t of ticks) console.log(t);
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("it matches the sample output", ticks, ['14:37:43', '14:37:44', '14:37:45', '14:37:46', '14:37:47', '14:37:48']);
test('six seconds gave six ticks', ticks.length, 6);
test('stopping it really stops it', (() => { const before = ticks.length; clock.advance(30); return ticks.length - before; })(), 0);
test('single digits are padded', formatTime(9 * 3600 + 5 * 60 + 3), '09:05:03');
test('midnight', formatTime(0), '00:00:00');
test('one second before midnight', formatTime(86399), '23:59:59');
test('it wraps at midnight instead of reading 24:00:00', formatTime(86400), '00:00:00');
test('and keeps wrapping', formatTime(86400 + 61), '00:01:01');
test('every tick has the right shape', ticks.every((t) => /^\d{2}:\d{2}:\d{2}$/.test(t)), true);
test('the ticks are one second apart', ticks.every((t, i) => i === 0 || Number(t.slice(-2)) === Number(ticks[i - 1].slice(-2)) + 1), true);
test('no real time was spent', true, true);
Adapted. The usual version prints for as long as you leave it running, which nothing can verify. Here the timer and the current time are arguments, so the test substitutes a clock it can fast-forward: six simulated seconds pass instantly and the six expected lines are asserted against the sample output. The real browser version is the commented line — one setInterval call.
Injecting the clock is not a testing trick, it is better design. The formatting is now a pure function of a number, so formatTime can be checked at midnight and at 23:59:59 without arranging for the test to run at those times. The wrap assertion matters: without % 86400 a clock counting past midnight reads 24:00:00.
Common mistakes
- Forgetting the padding. Without
padStart, five past nine shows as9:5:3. - Not wrapping at midnight. A count past 86399 shows
24:00:00and keeps climbing. - Losing the handle. If you don't keep what
setIntervalreturns, you can never stop it withclearInterval.
Try it yourself
- Make
formatTimeshow a 12-hour clock withAMorPM. - Use the fake clock to check that 23:59:58 ticks over to
00:00:00after two seconds. - Write a countdown that starts at 10 seconds and calls
stop()when it reaches00:00:00.