DEV Community

Indrakant Mishra
Indrakant Mishra

Posted on • Updated on

Create a timer in React with Start, Pause and Reset feature

Hello guys, i came across this task during my interview with a great company so i thought to share it with you all. The task is to create a countdown timer in React with Start, Pause and Reset features, so let's start building it -

// Import the useState hook from React for managing state
import { useState } from "react";

// Import the CSS file for styling
import "./styles.css";

// Define the main App component
export default function App() {
  // Initialize state variables for timer and timeInterval
  const [timer, setTimer] = useState(0);
  const [timeInterval, setTimeInterval] = useState(null);

  // Function to start the timer
  const startTimer = () => {
    // Use setInterval to update the timer every 1000 milliseconds (1 second)
    setTimeInterval(setInterval(() => {
      // Update the timer by incrementing the previous value by 1
      setTimer((prev) => prev + 1);
    }, 1000));
  }

  // Function to pause the timer
  const pauseTimer = () => {
    // Clear the interval to stop the timer from updating
    clearInterval(timeInterval);
  }

  // Function to reset the timer
  const resetTimer = () => {
    // Reset the timer value to 0
    setTimer(0);
    // Clear the interval to stop the timer
    clearInterval(timeInterval);
  }

  // Render the timer and buttons in the component
  return (
    <div className="App">
      <h3>Timer: {timer}</h3>
      <div className="btn-wrapper">
        {/* Button to start the timer */}
        <button onClick={startTimer}>Start</button>
        {/* Button to pause the timer */}
        <button onClick={pauseTimer}>Pause</button>
        {/* Button to reset the timer */}
        <button onClick={resetTimer}>Reset</button>
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is the complete code, i hope you found it informative and you can extend it to next level by setting a timer and decreasing it until 0. See you soon in the next post 😊

Top comments (2)

Collapse
 
mursalfk profile image
Mursal Furqan Kumbhar

Thank you so much for sharing this amazing code. However, I would suggest that before sharing the complete code, you should divide the code into smaller pieces and components and explain them a little bit as well, so that it is understandable by beginners as well.

Cool piece by the way. Keep sharing knowledge.

Collapse
 
indrakantm23 profile image
Indrakant Mishra

Thanks mate, sure will do that way from next time