LearnFrenzy
Sign in Take a free test

Closures · Closures Coding Problems · Question 9

A stopwatch with laps using closures in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write createStopwatch(now) with start, lap and stop methods that measure elapsed time using an injected clock, and print the laps for a simulated run.

Solution
main.js
function createStopwatch(now = Date.now) {
  let startedAt = null, lastLap = null;
  const laps = [];
  return {
    start() { startedAt = lastLap = now(); },
    lap() { const t = now(); laps.push(t - lastLap); lastLap = t; return laps.at(-1); },
    stop() { const total = now() - startedAt; return { total, laps: [...laps] }; },
  };
}

let clock = 0;
const sw = createStopwatch(() => clock);
sw.start();
clock = 1250; sw.lap();
clock = 2600; sw.lap();
clock = 3100;
const { total, laps } = sw.stop();
console.log(`laps: ${laps.join(" ms, ")} ms | total: ${total} ms`);

Output Verified by running it on Node.js

laps: 1250 ms, 1350 ms | total: 3100 ms

The start time, last lap time and the laps array are private state shared by the three methods. stop returns a copy of laps so callers cannot change the history.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links