SoFunction
Updated on 2025-04-07

React implements countdown function component

Story background

Countdown (or time display) is a common task in daily development

Commonly used in permission control or date display

Since it is often used, it is packaged into a component for later reuse

Project structure construction

npx create-react-app test-countdown --template=typescript
yarn add antd

Countdown component

1. Content in

// 
/* eslint-disable @typescript-eslint/no-useless-constructor */
import React from 'react';
import { Tooltip, Modal, Button } from "antd";
import './';
// In secondsfunction convertSecondsToHMS(seconds: number) {
  const hours = (seconds / 3600);
  const minutes = ((seconds % 3600) / 60);
  const remainingSeconds =  (seconds % 60);
  const formattedTime = `${hours}Hour ${minutes}minute ${remainingSeconds}Second`;
  return formattedTime;
}
// Countdown component props formattype IProps = {
  level: boolean;
  timeRemain: number;
}
// Countdown component state formattype IState = {
  level: boolean;
  timeRemain: number;
  lastMountedTime: number;
  timeCountdown: number;
  timer: any;
}
// Countdown componentclass App extends <IProps, IState> {
  state = {
    lastMountedTime: 0,
    timeRemain: 0,
    timeCountdown: 9999,
    level: false,
    timer: null,
  }
  // Extra constructor  constructor(props: IProps) {
    super(props);
  }
  // After the component is built, you need to save the level set in props and countdown to the state  // In addition, the local time needs to be saved in the state as a reference for subsequent calculations  // Finally turn on the timer and save the handle of the timer to the state  componentDidMount(): void {
    const { timeRemain, level } = ;
    const lastMountedTime = +new Date();
    const timer = setInterval(
      () => {
        (()=>({
          timeCountdown:  - (+new Date() - ) / 1000,
        }))
      }, 200
    )
    ({
      lastMountedTime,
      timeRemain,
      level,
      timer,
    })
  }
  // The timer needs to be released before the component is uninstalled  componentWillUnmount(): void {
    if() clearInterval();
  }
  // If the user is VIP, the remaining time of access is not displayed on tooltip  // If the user is a visitor, the font becomes red and the tooltip displays the countdown  // If the countdown is 0, a modal box will pop up to notify the user of the end of the trial  render() {
    const info =  ? 'VIP User' : 'Guest Mode';
    const fontColor =  ? 'black' : 'red';
    const timeCountdown =  > 0 ?  : 0;
    const toolTipInfo =  ? '' : convertSecondsToHMS(timeCountdown);
    return (
      <div className="App">
        {
          timeCountdown > 0 ? (
            <Tooltip
              title={toolTipInfo}
              placement="top"
            >
              <span
                style={{
                  color: fontColor
                }}
              >{info}</span>
            </Tooltip>
          ) : (
            <Modal
              open={true}
              destroyOnClose={true}
              getContainer={() => }
              onCancel={() => { ('') }}
              closable={true}
              maskClosable={true}
              title={`Authorization expires`}
              footer={[
                <Button size="small" onClick={() => { ('') }}>
                  Cancel
                </Button>,
              ]}
              width={215}
              bodyStyle={{
                padding: 0
              }}
            >
              <div>
                Your visitor mode has expired
              </div>
            </Modal>
          )
        }
      </div>
    )
  }
}
export default App;

2. Used in

// 
(
    <App timeRemain={5300} level={false}/>
);
// Strict mode is removed here

Two points of content

1. setInterval is just a trigger for internal state update of component

The calculated value of the timer is not used as the source of rendering, becausesetIntervalThe calculated value is inaccurate, especially when the page is switched to the background; therefore, the difference value of Date is used as the calculation basis.

2. Use of Tooltip and Modal for antd components

The countdown component is made using the antd component Tooltip and Modal. When its visitor time is exhausted, a modal box will pop up to notify the user to exit. This interactive mode is more friendly.

3. Countdown update immediately

use(()=>({}))Instead({}), to ensure time is updated immediately.

4. Controllable FPS

Since 1, it is known that the trigger is reducedsetIntervalThe interval can make the countdown display more silky.

This is the end of this article about the implementation of React countdown function components. For more related React countdown content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!