Stopwatch

A countdown timer with 'start', 'pause' and 'reset' functionality.

Exercise:

Create a stopwatch that counts down from a given number of seconds in the format mm:ss. Make it possible to start, pause, and reset the countdown. Make sure you can pass a callback function to the timer that is called when the displayed value is updated.

Solution:

The main part of this exercise boils down to modeling. If you find the right model, your life will be easy. If you use the wrong model, implementation will not only be hard, but the stopwatch might not reflect reality. Let’s define the state space of the application:

  • countdownInitialValue: the number of seconds initially set on the timer when instantiating it. When we reset the timer, its value will be set to this value.
  • secondsLeft: the current value of the countdown timer in seconds

How do we make time pass?

The easy part of the answer is that we need to use the setInterval function.

setInterval( callback, delay ) executes callback every delay milliseconds. Therefore, in theory, we could come up with the following solution:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.