25Implement a countdown timer with pause, resume and reset
easyAbout 15 minutesCodingtimersclosuresui
Problem
Implement two functions:
formatTime(ms): format a remaining time as"mm:ss", rounding up to the next whole second, so the display shows00:00only when the time is really over.createCountdown(durationMs, { interval = 1000, onTick, onComplete }): return a timer withstart(),pause(),resume(),reset(), and read-onlyremaining(milliseconds left) andrunning(boolean) properties.
formatTime(61000); // "01:01"
formatTime(59001); // "01:00"
const timer = createCountdown(5 * 60 * 1000, {
onTick: (ms) => (display.textContent = formatTime(ms)),
onComplete: () => alert("Time is up"),
});
timer.start();
timer.pause();
timer.resume();
timer.reset();Requirements
onTick(remaining)runs everyintervalwhile running.onCompleteruns exactly once, when the time reaches 0.- Do not drift: compute the remaining time from the clock, not by subtracting
intervalon every tick. Browsers delay timers, especially in background tabs. pause()freezesremaining;resume()continues from there.reset()stops the timer and restores the full duration.- Calling
start()twice must not create a second interval.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
Convert milliseconds to whole seconds with Math.ceil(ms / 1000): 59,001 ms still shows 01:00. Then minutes are Math.floor(seconds / 60), seconds are seconds % 60, and padStart(2, "0") adds leading zeros.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.