react 倒计时 hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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;

点击下方链接查看运行效果:

Edit react 倒计时 hook

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