vue和react实现自定义倒计时hooks
vue3,点击开始,然后按照传入需要倒计时的秒数,开始倒计时
export function useCountDown(inittime=60){
const time=ref<number>(0);
let timeId:any;
const start=()=>{
time.value=inittime;
timeId = setInterval(()=>{
time.value--;
if(time.value<=0){
clearInterval(timeId);
}
},1000)
}
onUnmounted(()=>{
clearInterval(timeId);
})
return {time,start}
}
react,点击开始,然后按照传入需要倒计时的秒数,开始倒计时
function useCountDown (time) {
const [num, setNum] = useState(0)
const ref = useRef(null)
// 调用这个方法,开始倒数
const start = () => {
clearInterval(ref.current);
setNum(time) // 重新赋值
// 定时器
ref.current = setInterval(() => {
setNum((num) => num - 1);
}, 1000)
}
// 倒数为0 关闭定时器
useEffect(
() => {
if (num === 0) {
clearInterval(ref.current) // 关闭定时器
}
},
[num]
)
useEffect(
() => {
return () => {
clearInterval(ref.current) // 关闭定时器
}
},
[]
)
// 返回可变值 与 触发函数
return {
num, // 可变值
start // 触发函数
}
}