Laps

The last part: laps. Runners and swimmers measure each lap with one click, while the stopwatch keeps running. Your stopwatch gets a Lap button.

The task. A click on Lap saves the time that the stopwatch shows at that moment. The laps are listed under the buttons, in a list with the class laps, newest first, each as Lap 2: 7.4: the number of the lap and its time. Reset empties the list. And since a lap makes sense only while the time is running, Lap is disabled while the stopwatch is stopped.

Tips:

  • Keep the laps in state as an array of objects, such as { number: 2, time: 74 }, with the time in tenths, as the stopwatch has it.
  • Newest first means that the new lap goes at the start of the array: setLaps((laps) => [newLap, ...laps]).
  • The number of the new lap is one more than the number of laps so far. Each lap has a different number, so it's a good key.

That's the whole project. Your stopwatch keeps three pieces of state: the time, whether it's running and the laps. One effect starts the interval while the stopwatch runs, and its cleanup stops it, whether Stop or Reset changed the state. In the next lesson, Refs and Custom Hooks, you'll put the cursor into a text field, keep values that the page doesn't show, and write hooks of your own.

Instructions

A click on Lap adds the current time to the list laps, newest first, as Lap 1: 2.3.

Reset empties the list of laps too.

Lap is disabled while the stopwatch is stopped.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

3/3

Next