Lesson 8 of 8
Stopwatch
- 15 min
- 6 checks
- 3 hints
- Go to task
Goal
Time comes from the clock, not from counting ticks
Explanation
The first idea that comes to mind when you build a stopwatch is to have setInterval bump a counter every tenth of a second. But the setInterval delay is a minimum, not a guaranteed schedule: ticks run late when the page is busy, and browsers slow timers in background tabs down to one tick per second, so ten minutes in the background turn into one minute on the counter.
The right way is to save the start time with Date.now(), then work out the elapsed time by subtraction every time you display it. The timer's only job is to decide when the screen gets updated, not to measure how much time has passed.
Watch out: to resume counting after a stop, you need to keep the time that built up before it and add it to the new stretch. And prevent double starts, because clicking "Start" twice creates two timers, and only one of them ever gets cleared.
Your task
Wire up the #start, #stop and #reset buttons, and show the seconds in #time with one decimal place (0.0, then 1.3), calculated from Date.now(). Make the "Reset" button stop the clock and set it back to 0.0.
Checks
6 checks- Starts at zero
- "Start" starts counting
- "Stop" freezes the time
- Resuming picks up where the clock stopped
- "Reset" stops the clock and sets it back to zero
- Time comes from the clock, not from counting ticks