如何在頁面中實現倒計時功能

moment計算兩個時間差值

moment(endTime).diff(moment(startTime), 'years')

moment(endTime).diff(moment(startTime), 'months')

moment(endTime).diff(moment(startTime), 'days')    //  開始時間和結束時間的時間差,以「天」爲單位;endTime和startTime都是毫秒數

moment(endTime).diff(moment(startTime),'minutes' )

moment(endTime).diff(moment(startTime), 'seconds')

原生實現

用當即執行函數封裝一個倒計時插件,裏頭用moment插件中的diff方法計算兩個時間段的差值,並以想要的形式返回,默認以毫秒差形式返回html

//定義一個當即執行的函數
(function () {
    var Ticts=function Ticts() {
        this.ticts = {};
    };
    Ticts.prototype.createTicts=function(id, dealline) {
        var ticts=this;
        var time=moment(dealline).diff(moment());
        var _ticts=this.ticts[id] = {
            dealine: dealline
            , id: id
            , time: time
            , interval: setInterval(function () {
                var t = null;
                var d = null;
                var h = null;
                var m = null;
                var s = null;
         //js默認時間戳爲毫秒,須要轉化成秒
                t = _ticts.time / 1000;
                d = Math.floor(t / (24 * 3600));
                h = Math.floor((t - 24 * 3600 * d) / 3600);
                m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60);
                s = Math.floor((t - 24 * 3600 * d - h * 3600 - m * 60));
         //這裏能夠作一個格式化的處理,甚至作毫秒級的頁面渲染,基於DOM操做,太多個倒計時一塊兒會致使頁面性能降低
                document.getElementById(id).innerHTML = d + '天' + h + '小時' + m + '分鐘' + s + '秒';
                _ticts.time -= 1000;
                if (_ticts.time < 0)
           ticts.deleteTicts(id);//判斷是否到期,到期後自動刪除定時器
            }, 1000)
        }
    };
    Ticts.prototype.deleteTicts = function(id) {
        clearInterval(this.ticts[id].interval);//清楚定時器的方法,須要定時器的指針做爲參數傳入clearInterval
        delete this.ticts[id];//經過delete的方法刪除對象中的屬性
    };
   //新建一個ticts對象,放到window全局函數中,那麼在html頁面是(或者其餘js文件)能夠訪問該對象
    window.Ticts=new Ticts();
})();

React實現

import React from 'react';
import moment from 'moment';

interface props {
  deadline: number; // 截止時間戳
}

const CountDown = (props: IProps) => {

  const { deadline } = props;

  const [time, setTime] = useState(Date.now());
  
  useEffect(() => {
    let timer: NodeJS.Timeout | null = null;
    if (deadline && deadline > time) {
      timer = setInterval(() => {
        if (deadline - time < 1000 && timer) {
          if (timer) clearInterval(timer);
        }
        setTime(Date.now());
      }, 1000);
    }
    return () => {
      if (timer) clearInterval(timer);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deadline]);
  
  const format = () => {
    const t = moment(deadline).diff(moment(time), 'seconds');
    const d = Math.floor(t / (24 * 3600));
    const h = Math.floor((t - 24 * 3600 * d) / 3600);
    const m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60);
    const s = Math.floor(t - 24 * 3600 * d - h * 3600 - m * 60);
    return [d * 24 + h, m, s];
  };
  
  const countDown = format();

  return (
    <span>還剩{countDown[0]}小時{countDown[1]}分鐘{countDown[2]}秒</span>
  )
}
相關文章
相關標籤/搜索