Overview
In this exercise, you will be building a timer component using React. The timer should be able to start, pause, and reset. You can use any styling library of your choice.
Requirements
The timer should display minutes and seconds in the format of
MM:SS
.The timer should have a start button that starts the timer.
The timer should have a pause button that pauses the timer.
The timer should have a reset button that resets the timer to 00:00.
The timer should not display negative numbers.
The timer should be accurate and not drift over time.
The timer should not be able to start multiple times without resetting or pausing first.
Instructions
Create a new React project using create-react-app.
Create a new component called
Timer
.Implement the requirements listed above.
Test your component thoroughly.
Once you are satisfied with your implementation, create a new Git repository and push your code.
Bonus Requirements
Add a feature to set the timer duration in minutes.
Add a feature to play a sound when the timer reaches 00:00.
Add a feature to allow the user to change the font size and color of the timer display.
Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. 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 has three button elements: start, pause, and reset. Clicking the start button sets the timerOn
state to true, which triggers the useEffect
hook to start updating the time. Clicking the pause button sets the timerOn
state to false, which stops the interval. Clicking the reset button sets the time and timerOn
state back to their initial values.
The formatTime
function takes the current time in seconds and returns a formatted string in the format MM:SS
. This function is used to display 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. The font size is calculated by multiplying the duration by 20.
Applications where the Timer component can be used
Fitness application - A workout app that tracks time spent on exercises such as planks, push-ups, or squats. The
Timer
component can be used to display the elapsed time for each exercise and to alert the user when the exercise is complete.Cooking application - A recipe app that includes a timer feature to help users keep track of cooking times. The
Timer
component can be used 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.Productivity application - A task management app that includes a Pomodoro timer feature. The
Timer
component can be used to display the elapsed time for each Pomodoro cycle (25 minutes of focused work followed by a 5-minute break).Educational application - An app that helps users learn a new language or memorize facts. The
Timer
component can be used to display the elapsed time for studying or taking a quiz and to alert the user when the time is up.Game application - A puzzle or strategy game that includes timed levels or challenges. The
Timer
component can be used to display the elapsed time for each level, and to alert the user when time is running out.Music application - A metronome app that helps musicians keep a steady beat. The
Timer
component can be used to display the elapsed time for each beat, and to alert the user when it's time to change tempo.Financial application - A budgeting app that includes a feature for tracking expenses. The
Timer
component can be used to track the time spent on each expense, helping users to identify where their money is going.
The Timer
component is a useful feature for a wide range of applications, from fitness and cooking apps to educational and financial tools. With the ability to customize the appearance and functionality of the timer, developers can create a unique user experience tailored to the specific needs of their application. Whether tracking time spent on a task, completing a workout routine, or studying for an exam, the Timer
component can help users stay on track and achieve their goals.
Thanks for taking this JavaScript exercise!
I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!
If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.
And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.