React Timer – JavaScript Exercise #7

Overview

In this task, you’ll create a React timer component that can start, pause, and reset. Additionally, you’re free to select any styling library you prefer.

Requirements for React Timer

  1. Display minutes and seconds in the timer using the MM:SS format.
  2. Add a start button that starts the timer.
  3. Provide a pause button that pauses the timer.
  4. Add a reset button to the timer that resets it to 00:00.
  5. Prevent the timer from displaying negative numbers.
  6. Ensure the timer remains accurate and does not drift over time.
  7. Prevent the timer from starting multiple times without first resetting or pausing.

Instructions

  1. Create a new React project using create-react-app.
  2. Create a new component called Timer.
  3. Implement the requirements listed above.
  4. Test your component thoroughly.
  5. Once you satisfy yourself with your implementation, create a new Git repository and push your code.

Bonus Requirements

  1. Add a feature to set the timer duration in minutes.
  2. Add a feature that triggers a sound when the timer reaches 00:00.
  3. Add a feature to allow the user to change the font size and color of the timer display.

Before you look at the final output, I encourage you to spend some time working through the exercise on your own. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Timer exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Timer exercise

import React, { useState, useEffect, useRef } from 'react';

const Timer = () => {
  const [time, setTime] = useState(0);
  const [timerOn, setTimerOn] = useState(false);
  const [duration, setDuration] = useState(1); // Bonus feature

  const intervalRef = useRef(null);

  useEffect(() => {
    if (timerOn) {
      intervalRef.current = setInterval(() => {
        setTime((prevTime) => prevTime + 1);
      }, 1000);
    }

    return () => {
      clearInterval(intervalRef.current);
    };
  }, [timerOn]);

  const handleStart = () => {
    if (!timerOn) {
      setTimerOn(true);
    }
  };

  const handlePause = () => {
    if (timerOn) {
      setTimerOn(false);
    }
  };

  const handleReset = () => {
    setTime(0);
    setTimerOn(false);
  };

  const formatTime = (time) => {
    const minutes = Math.floor(time / 60)
      .toString()
      .padStart(2, '0');
    const seconds = (time % 60).toString().padStart(2, '0');
    return `${minutes}:${seconds}`;
  };

  return (
    <div>
      <div style={{ fontSize: `${duration * 20}px` }}> {formatTime(time)}</div>
      <div>
        <button onClick={handleStart} disabled={timerOn}>
          Start
        </button>
        <button onClick={handlePause} disabled={!timerOn}>
          Pause
        </button>
        <button onClick={handleReset}>Reset</button>
      </div>
      <div>
        {/* Bonus feature */}
        <label>
          Duration:
          <input
            type="number"
            value={duration}
            onChange={(e) => setDuration(parseInt(e.target.value))}
          />
        </label>
      </div>
    </div>
  );
};

export default Timer;

The Timer component uses useState hooks to store the current time, whether the timer is on or off, and the duration of the timer (bonus feature). It also uses a useEffect hook to update the time every second when the timer is on. The useRef hook is used to store a reference to the interval so that it can be cleared when the component unmounts.

The component includes three buttons: start, pause, and reset. When the start button is pressed, the timerOn state is set to true, activating the useEffect hook to begin updating the time. Pressing the pause button changes the timerOn state to false, which stops the interval. The reset button restores both the time and timerOn state to their original values.

The formatTime function takes the current time in seconds and returns a formatted string in the format MM:SS. This function displays the time on the screen.

The bonus feature allows the user to change the font size of the timer display by adjusting the duration input value. For example, multiply the duration by 20 to calculate the font size.

Applications utilizing the React Timer component

  1. Fitness application – A workout app that tracks time spent on exercises such as planks, push-ups, or squats. The app uses The Timer component to display the elapsed time for each exercise and to alert the user when the exercise is complete.
  2. Cooking application – A recipe app that includes a timer feature to help users keep track of cooking times. The app uses the The Timer component to display the elapsed time for each step of a recipe and can alert the user when it’s time to move on to the next step.
  3. Productivity application – A task management app that includes a Pomodoro timer feature. The app uses The Timer component to display the elapsed time for each Pomodoro cycle (25 minutes of focused work followed by a 5-minute break).
  4. Game application – A puzzle or strategy game that includes timed levels or challenges. The Timer component is used to display the elapsed time for each level, and to alert the user when time is running out.

The Timer component serves as a valuable feature across a variety of applications, including fitness and cooking apps, as well as educational and financial tools. Its customizable appearance and functionality allow developers to design a unique user experience that meets the specific requirements of their application.

Thanks for taking this JavaScript exercise!

Whether users are tracking time for a task, finishing a workout, or preparing for an exam, the Timer component keeps them focused and supports their goals. I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practicing and experimenting with React, and you’ll be well on your way to becoming a skilled React developer!

Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top