前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react 倒计时 hook

react 倒计时 hook

原创
作者头像
小鑫
发布2022-04-25 15:30:58
7660
发布2022-04-25 15:30:58
举报
文章被收录于专栏:小鑫の随笔小鑫の随笔
代码语言:javascript
复制
import { useRef, useState, useEffect } from 'react';

/**
 * 解析毫秒为天、时、分、秒
 * @param milliseconds 毫秒
 */
const parseMs = (milliseconds: number) => {
  return {
    days: Math.floor(milliseconds / 86400000),
    hours: Math.floor(milliseconds / 3600000) % 24,
    minutes: Math.floor(milliseconds / 60000) % 60,
    seconds: Math.floor(milliseconds / 1000) % 60,
  };
};

/**
 * 倒计时
 * @param endTimeStamp 结束时间的时间戳
 */
const useCountDown = (endTimeStamp: number) => {
  const timer = useRef(0);
  const [state, setState] = useState(endTimeStamp);

  // 计算时间的差值
  const calcTimeDiff = () => {
    // 获取当前时间戳
    const currentTime = +new Date();
    // 计算当前时间和结束时间的差值
    const seconds = Math.floor((endTimeStamp || 0) - currentTime);
    // 如果是负数 就清空定时器
    if (seconds <= 0) {
      clearInterval(timer.current);
      return setState(0);
    }
    setState(seconds);
  };

  useEffect(() => {
    calcTimeDiff();
    timer.current = setInterval(() => {
      calcTimeDiff();
    }, 1000);
    return () => {
      clearInterval(timer.current);
    };
  }, []);

  const { days, hours, minutes, seconds } = parseMs(state);
  return { days, hours, minutes, seconds };
};

export default useCountDown;

点击链接查看运行效果:https://codesandbox.io/s/elastic-wood-yomiu?fontsize=14&hidenavigation=1&theme=dark

github:https://github.com/isxiaoxin/front_end_wheel

首发自:react 倒计时 hook - 小鑫の随笔

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档