The Wayback Machine - https://web.archive.org/web/20240905200858/https://www.geeksforgeeks.org/how-to-create-a-countdown-timer-using-reactjs/
Open In App

How to Create Countdown Timer in React JS

Last Updated : 04 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

React timers are very common UI components that are widely used in various applications and websites to visually display the remaining time for a specific activity or event. React timers are mostly used to highlight the commencement or conclusion of events or offers on commercial websites.

This tutorial explores the process of creating a countdown timer using React JS, a popular JavaScript user interface toolkit.

Preview of final output:

countdown timer with react output

Output Preview

Prerequisites

Approach to Create a Countdown Timer Using React JS

Here, we have 2 approaches to create the countdown timer given below

  1. Using React Hooks with Functional Components
  2. Using React State with the Class based Components

Steps to Create Countdown Timer Using React JS

Before creating a timer in React JS, you should be familiar with these terminologies:

  • getTimeRemaining: Compute the difference between the target timer and the current time we have. This function will check the time left from the target timer by doing calculations and return a total number of hours, minutes, and seconds.
  • StartTimer: This function will start timing down from getting a total number of hours, minutes, and seconds from the getTimeRemaining function.
  • ClearTimer: This function is used to reset the timer, which means If you restart the timer it clears the time remaining from the previous countdown, otherwise it starts parallel two-timing down or it may collapse each other.
  • getDeadTimer: This function provides the deadline of the timer means it gives time from where you want to start the countdown. In this, you have to add time if you want to extend. We have used this in two scenarios first when the page is loaded and second when someone clicks the reset button.

Steps to Create React Application

First, let’s make a sample React web application, on which we will put a React timer.

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Approach 1: Create Countdown Timer Using React Hooks

We can create a countdown timer using React hooks and the setInterval method of JavaScript.

We use React hooks like useState, useRef and useEffect

We have provided the working code to properly demonstrate how to create a countdown timer using the React Hooks with Functional Components.

React Countdown Timer using React Hooks Example

This example implements a countdown timer in React using React Hooks and the JavaScript setInterval() method.

Javascript




// Filename - App.js
 
import React, { useState, useRef, useEffect } from "react";
 
const App = () => {
    // We need ref in this, because we are dealing
    // with JS setInterval to keep track of it and
    // stop it when needed
    const Ref = useRef(null);
 
    // The state for our timer
    const [timer, setTimer] = useState("00:00:00");
 
    const getTimeRemaining = (e) => {
        const total =
            Date.parse(e) - Date.parse(new Date());
        const seconds = Math.floor((total / 1000) % 60);
        const minutes = Math.floor(
            (total / 1000 / 60) % 60
        );
        const hours = Math.floor(
            (total / 1000 / 60 / 60) % 24
        );
        return {
            total,
            hours,
            minutes,
            seconds,
        };
    };
 
    const startTimer = (e) => {
        let { total, hours, minutes, seconds } =
            getTimeRemaining(e);
        if (total >= 0) {
            // update the timer
            // check if less than 10 then we need to
            // add '0' at the beginning of the variable
            setTimer(
                (hours > 9 ? hours : "0" + hours) +
                ":" +
                (minutes > 9
                    ? minutes
                    : "0" + minutes) +
                ":" +
                (seconds > 9 ? seconds : "0" + seconds)
            );
        }
    };
 
    const clearTimer = (e) => {
        // If you adjust it you should also need to
        // adjust the Endtime formula we are about
        // to code next
        setTimer("00:00:10");
 
        // If you try to remove this line the
        // updating of timer Variable will be
        // after 1000ms or 1sec
        if (Ref.current) clearInterval(Ref.current);
        const id = setInterval(() => {
            startTimer(e);
        }, 1000);
        Ref.current = id;
    };
 
    const getDeadTime = () => {
        let deadline = new Date();
 
        // This is where you need to adjust if
        // you entend to add more time
        deadline.setSeconds(deadline.getSeconds() + 10);
        return deadline;
    };
 
    // We can use useEffect so that when the component
    // mount the timer will start as soon as possible
 
    // We put empty array to act as componentDid
    // mount only
    useEffect(() => {
        clearTimer(getDeadTime());
    }, []);
 
    // Another way to call the clearTimer() to start
    // the countdown is via action event from the
    // button first we create function to be called
    // by the button
    const onClickReset = () => {
        clearTimer(getDeadTime());
    };
 
    return (
        <div
            style={{ textAlign: "center", margin: "auto" }}>
            <h1 style={{ color: "green" }}>
                GeeksforGeeks
            </h1>
            <h3>Countdown Timer Using React JS</h3>
            <h2>{timer}</h2>
            <button onClick={onClickReset}>Reset</button>
        </div>
    );
};
 
export default App;


Steps To Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000

Working React countdown timer

Explanation:

  • First, initialize a state ‘timer‘ and a ref ‘Ref‘ to manage time and interval.
  • useEffect Hook starts the timer by calling clearTimer.
  • getTimeRemaining Function calculates the remaining time from a future deadline
  • startTimer Function updates the timer display every second based on the remaining time.
  • clearTimer Function resets the timer to 10 seconds and starts the countdown.
  • getDeadTime Function calculates the deadline time for the countdown.
  • onClickReset Function resets the timer to 10 seconds when the “Reset” button is clicked.
  • Return JSX displays the timer value and a “Reset” button in the UI.

Approach 2: Create Countdown Timer Using React State in Class Components

We can create a countdown timer using React states in class components and the setInterval method of JavaScript.

We will be using the React setState method and createRef methods to updated the timer in the state variable.

We have provided the working code to properly demonstrate how to create a countdown timer using the React States with Class Components.

Countdown timer using React States Example:

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    constructor(props) {
        super(props);
 
        // We need ref in this, because we are dealing
        // with JS setInterval to keep track of it and
        // stop it when needed
        this.Ref = React.createRef();
 
        // The state for our timer
        this.state = {
            timer: "00:00:00",
        };
    }
 
    getTimeRemaining = (e) => {
        const total = Date.parse(e) - Date.parse(new Date());
        const seconds = Math.floor((total / 1000) % 60);
        const minutes = Math.floor((total / 1000 / 60) % 60);
        const hours = Math.floor((total / 1000 / 60 / 60) % 24);
        return {
            total,
            hours,
            minutes,
            seconds,
        };
    };
 
    startTimer = (e) => {
        let { total, hours, minutes, seconds } = this.getTimeRemaining(e);
        if (total >= 0) {
            // update the timer
            // check if less than 10 then we need to
            // add '0' at the beginning of the variable
            this.setState({
                timer:
                    (hours > 9 ? hours : "0" + hours) +
                    ":" +
                    (minutes > 9 ? minutes : "0" + minutes) +
                    ":" +
                    (seconds > 9 ? seconds : "0" + seconds),
            });
        }
    };
 
    clearTimer = (e) => {
        // If you adjust it you should also need to
        // adjust the Endtime formula we are about
        // to code next
        this.setState({ timer: "00:00:10" });
 
        // If you try to remove this line the
        // updating of timer Variable will be
        // after 1000ms or 1sec
        if (this.Ref.current) clearInterval(this.Ref.current);
        const id = setInterval(() => {
            this.startTimer(e);
        }, 1000);
        this.Ref.current = id;
    };
 
    getDeadTime = () => {
        let deadline = new Date();
 
        // This is where you need to adjust if
        // you extend to add more time
        deadline.setSeconds(deadline.getSeconds() + 10);
        return deadline;
    };
 
    // We can use componentDidMount so that when the component
    // mount the timer will start as soon as possible
    componentDidMount() {
        this.clearTimer(this.getDeadTime());
    }
 
    // Another way to call the clearTimer() to start
    // the countdown is via action event from the
    // button first we create function to be called
    // by the button
    onClickReset = () => {
        this.clearTimer(this.getDeadTime());
    };
 
    render() {
        return (
            <div style={{ textAlign: "center", margin: "auto" }}>
                <h1 style={{ color: "green" }}>GeeksforGeeks</h1>
                <h3>Countdown Timer Using React JS</h3>
                <h2>{this.state.timer}</h2>
                <button onClick={this.onClickReset}>Reset</button>
            </div>
        );
    }
}
 
export default App;


Output: Now open your browser and go to http://localhost:3000

Working React countdown timer

Explanation:

  • First, initialize a state ‘timer‘ and a ref ‘Ref‘ using createRef() to manage time and interval.
  • In componentDidMount initiate the countdown by calling the clearTimer function.
  • getTimeRemaining Function calculates the remaining time from a future deadline
  • startTimer Function updates the timer display every second based on the remaining time.
  • clearTimer Function resets the timer to 10 seconds and starts the countdown.
  • getDeadTime Function calculates the deadline time for the countdown.
  • onClickReset Function resets the timer to 10 seconds when the “Reset” button is clicked.
  • Return JSX displays the timer value and a “Reset” button in the UI.

Wrapping Up

React timer is a very useful component in website UI, as it helps in making events more interactive. This tutorial teaches how to create a countdown timer using React JS for your projects. Explained with live working code, this guide provides an easy solution to build a React timer.

We have used React Hooks and setTimer() method to create a countdown timer in React JS. Hope this guide, helps you build your first timer using React JS.



Similar Reads

How to Create Countdown Timer using React Native ?
Our main objective focuses on constructing a straightforward and use­r-friendly countdown timer that impeccably showcase­s the remaining time le­ft in terms of years, days, hours, minutes, and seconds until a specific date. To set up your de­velopment environment, begin by installing Node.js. Next, utilize the Expo CLI edition to seamle­ssly execut
4 min read
Event Countdown Timer Using React
Event Countdown Timer is an application where you can create an event with the name, date, and category of the event and it will create a card that will show you the remaining time of the event. After reaching that time of the day it will notify you. The application will provide the option to start, stop and pause the countdown timer . Project will
5 min read
How To Create A Countdown Timer Using JavaScript
A countdown timer is an accurate timer that can be used for a website or blog to display the countdown to any special event, such as a birthday or anniversary. The basics of a countdown timer are : Set a valid end date.Calculate the time remaining.Convert the time to a usable format.Output the clock data as a reusable object.Display the clock on th
5 min read
How to Add a Countdown Timer in WordPress?
Countdown timers are become the prevalent tool for creating the user engagement and to create urgency on websites. This would strategically generate the sense of urgency and prompting visitors to take an action before the limited window of opportunity closes. Here in this blog post, you will learn how to create a countdown timer for your WordPress
2 min read
Create a Event Countdown App with React Native
In this article, we will create an event countdown time application using React Native. The Eve­nt Countdown App is a mobile application develope­d with React Native. It enable­s users to effortlessly cre­ate and monitor countdown timers for differe­nt events. By providing the e­vent title, sele­cting a category, and specifying the date­ and time,
7 min read
Create Timer Based Phone Silencer App using React-Native
In this project, we will create a mobile application using React Native that acts as a timer-based phone silencer. The app allows users to set a timer, and when the timer finishes, it automatically silences the phone. A notification will be displayed to inform the user that the phone is now silenced. Prerequisite:React NativeReact Native Components
3 min read
Create a Quiz App using React Hooks and Timer-Based State Management
Quiz Application is a web-based application built using React Hooks and Timer-Based State Management. It provides users with a series of multiple-choice questions and requires them to select an option within a given time limit. If the user fails to select an option within the specified time, the application automatically moves to the next question.
5 min read
Create a Countdown using Bootstrap 5
The countdown timer displays the remaining time from a set future date, showing days, hours, minutes, and seconds until the specified event or deadline. In this article, we will create a countdown timer using Bootstrap. Preview Prerequisites HTMLCSSJavaScriptBootstrapApproachThe provided HTML, CSS, and JavaScript create a countdown timer. Initially
3 min read
How to create Coming Soon Page with Countdown in Bootstrap ?
A Coming Soon countdown landing page is a great way to build anticipation for your website or startup. It not only keeps visitors up to date with upcoming releases but also adds excitement. Thanks to Bootstrap’s responsive design and components, the Coming Soon is seamless, ensuring your audience gets a memorable first impression. Output Preview: L
4 min read
Creating a Timer Component with useEffect Hook in React
Timer Component using React along with its useEffect hook will not only display the elapsed time since the component mounts but also allow users to set and manage the countdown timer dynamically. We will harness the power of the useEffect hook to manage side effects and update the timer seamlessly. Output Preview: Let us have a look at how the fina
5 min read
Create a Pomodoro Timer using HTML CSS and JavaScript
In this article, we will see how to design Pomodoro Timer with the help of HTML CSS, and JavaScript. The Pomodoro Technique is a time management method that involves breaking your work into focused intervals, typically 25 minutes, followed by short breaks. After completing four cycles, take a longer break. This technique aims to enhance productivit
3 min read
Create a Quiz App with Timer using HTML CSS and JavaScript
In this tutorial, we'll guide you through the process of building an engaging Quiz App with a built-in timer, utilizing HTML, CSS, and JavaScript. This application is designed to present users with a curated set of questions, each accompanied by a countdown timer, providing an interactive and time-bound quiz experience. Additionally, the app keeps
7 min read
Create A Download Button with Timer in HTML CSS and JavaScript
In this article, we will discuss how to create a Download button with a timer attached to it using HTML, CSS, and Javascript. Our goal is to create a button that has a timer attached to it. The download should only start after the timer has run out, which we will achieve using the setTimeout and setInterval functions of JavaScript. We will use thes
2 min read
Google AMP amp-date-countdown
The amp-data-countdown is used to count down to a specific date which is rendered to the AMP HTML page. It is specifically used as a timer or count-down. Required Scripts: Adding the amp-data-countdown component. C/C++ Code &lt;script async custom-element=&quot;amp-date-countdown&quot; src= &quot;https://cdn.ampproject.org/v0/amp-date-countdown-0.1
2 min read
D3.js timer.stop() Function
The timer.stop() function in D3.js is used to stop the current ongoing timer function thus preventing further calls to the function. This function will only work if the timer has not stopped yet. Syntax: timer.stop() Parameters: It takes no parameters. Returns: It does not return anything. Note: The Output should be different when run different tim
2 min read
D3.js timer.restart() Function
The timer.restart() function in D3.js is used to restart a timer with the given function and delay. The timer.restart() function is used when one wants to reset the timer and start again. Syntax: timer.restart(callback, delay); Parameters: It takes two parameters as mentioned above and described below: callback: It is the function to be stopped or
2 min read
D3.js timer() function
The D3.timer() function is used to run a timer function after a particular interval of time. The timer will run after a specified delay. The delay given is in milliseconds. Syntax: d3.timer(callback, delay); Parameters: It takes the following two parameters. callback: It is a function.delay: It is the delay after which the function is executed. Ret
1 min read
Node.js Immediate Timer Class
The timer module is used for scheduling functions which will be called at some future period of time. It is a global API So, there is no need to import (require("timers")) to use it. Immediate Class has an object (setImmediate()) which is created internally to scheduled actions, and (clearImmediate()) can be passed in order to cancel those schedule
2 min read
Node.js Timeout Timer Class
The timer module is used for scheduling functions which will be called at some future period of time. It is a global API So, there is no need to import (require("timers")) to use it. Timeout Class has an object (setTimeout()/setInterval()) which is created internally to scheduled actions, and (clearTimeout()/clearInterval()) can be passed in order
3 min read
How to Start and Stop a Timer in PHP ?
You can start and stop a timer in PHP using the microtime() function in PHP. The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds. In this article, you will learn the uses of the microtime() function. Syntax: microtime( $get_as_float )Parameters: The $get_as_float is sent as a p
2 min read
Describe the use of Timer methods in Node.js
In this article, we are going to explore timers in Node.js and how to use them in various scenarios. The timers method in node.js contains different types of functions that are used for executing a block of code or a function at a specific period of time. It is a global module that is not required to be imported. We can divide the timers module int
3 min read
Moment.js Timer Plugin
The Moment.js Timer Plugin is used for the creation of timers. It is an improvement over JavaScript's native timer. Essentially, it is a rewriting of the setInterval and setTimeout methods. It provides a list of functions concerned with creating and managing timers on top of moment duration objects. It can be installed using the following command:
1 min read
Foundation CSS JavaScript Timer Utility
Foundation CSS is a responsive front-end framework for web development. It includes a variety of CSS and JavaScript utilities that can be used to build and style web applications. One of the JavaScript utilities included in Foundation is a timer utility, which can be used to execute a function after a specified amount of time has passed. Syntax : v
3 min read
Design a Timer using Tailwind CSS
In this project, we'll design a Timer using Tailwind CSS a utility-first CSS framework. A timer counts down from a specified interval and notifies the user upon completion. We'll create an attractive and responsive interface for easy interaction. ApproachFirst define the layout of the timer interface using the HTML elements.Apply Tailwind CSS class
2 min read
Building a Pomodoro Timer with VueJS
A Pomodoro Timer is a time management tool that helps individuals break work into the intervals traditionally 25 minutes in the length separated by the short breaks. This timer will allow users to start, stop and reset the timer as needed with the visually appealing user interface. Prerequisites:HTMLVue.jsApproachInitialization: We start by setting
3 min read
JavaScript Timer
A timer has been shown that shows the countdown, and its color/message gets changed after every specific period. Prerequisites: GetMinutes()GetSeconds()SetInterval() MethodSyntax: setTimeout(function, milliseconds, parameter1, ...);Parameter:AttributeDescriptionfunctionIt is the function that will be executed.millisecondsIt is the number of millise
2 min read
How to add Timer in Next.js ?
In this article, we are going to learn how we can add Timer in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally. ApproachTo add our Timer we are going to use the
2 min read
Create a New React App - npm create-react-app
The create react app command allows us to create a development environment and install all necessary libraries for creating single-page applications using React. The CRA tool is used to set up a new React project quickly, providing a standard structure and configuration. It includes a development server, build scripts, and support for modern JavaSc
3 min read
Create a Card View in React native using react-native-paper
React Native is a framework developed by Facebook for creating native-style apps for iOS &amp; Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render mobile UIs for both platforms. Approach: In this ar
2 min read
Create an Activity Indicator in react-native using react-native-paper library
React Native is a framework developed by Facebook for creating native-style apps for iOS &amp; Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render mobile UIs for both platforms. Prerequisites: Basic
2 min read