iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
自我挑戰組

從零開始學習React 系列 第 28

Day28 React - Countdown Timer

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20211013/201398003TePEM2OgT.png

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

const Ctime = () => {
    const [timerDays, setTimerDays] = useState('00');
    const [timerHours, setTimerHours] = useState('00');
    const [timerMinutes, setTimerMinutes] = useState('00');
    const [timerSeconds, setTimerSeconds] = useState('00');

    let interval = useRef();

    const startTime =() => {
        const countdownDate = new Date('Oct 15, 2021 00:00:00').getTime();

        interval = setInterval(()=>{
            const now = new Date().getTime();
            const distance = countdownDate - now;

            const days = Math.floor(distance / (1000*60*60*24));
            const hours = Math.floor((distance % (1000*60*60*24)) / (1000*60*60));
            const minutes = Math.floor((distance % (1000*60*60)) / (1000*60));
            const seconds = Math.floor((distance % (1000*60))/ 1000);

            if (distance<0){
                
                clearInterval(interval.current);
            }else{
                
                setTimerDays(days);
                setTimerHours(hours);
                setTimerMinutes(minutes);
                setTimerSeconds(seconds);
            }

        },1000);
    };

   
    useEffect(() => {
        startTime();
        return () => {
            clearInterval(interval.current);
        };
    });


    return (
        <div>
           <div class="container">         
            <div className="content">
              <h3 className="title">Countdown Timer</h3>
              <p className="description">鐵人賽完賽日期倒數計時</p>
             <div className="count-down">
                 <div className="box">
                   <h3 id="days">{timerDays}</h3>
                   <p>days</p>
                 </div>
                 <div className="box">
                   <h3 id="hours">{timerHours}</h3>
                   <p>hours</p>
                 </div>
                 <div className="box">
                   <h3 id="minutes">{timerMinutes}</h3>
                   <p>minutes</p>
                 </div>
                 <div className="box">
                   <h3 id="seconds">{timerSeconds}</h3>
                   <p>seconds</p>
                 </div>
                </div>       
              </div>
            </div> 
        </div>
    )
}

export default Ctime

上一篇
Day27 Router useParams 小實作
下一篇
Day29 React - Styled-Components
系列文
從零開始學習React 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言