Lesson 8 of 8

Stopwatch

Goal

Time comes from the clock, not from counting ticks

01

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.

02

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
  1. Starts at zero
  2. "Start" starts counting
  3. "Stop" freezes the time
  4. Resuming picks up where the clock stopped
  5. "Reset" stops the clock and sets it back to zero
  6. Time comes from the clock, not from counting ticks
03

Hints

0/3
Track lessons0 of 8 done

Build from scratch, on your own, the components you'll find on almost every website, such as tabs, dialogs, tables, toasts and a carousel.

Advanced level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Build from scratch, on your own, the components you'll find on almost every website, such as tabs, dialogs, tables, toasts and a carousel.

Advanced level, 8 lessons, 2 hours in total.