import { useEffect, useRef, useState } from 'react'
export default function useCountDown (initCount = 10, callBack = () => {}) {
const timeId = useRef<{id:number}>({ id: 0 })
const [count, setCount] = useState(initCount)
const start = () => {
setCount(initCount)
timeId.current.id = window.setInterval(() => {
setCount((count) => count - 1)
}, 1000)
}
useEffect(() => {
return () => {
clearInterval(timeId.current.id)
}
}, [])
useEffect(
() => {
if (count === 0) {
clearInterval(timeId.current.id)
callBack()
}
},
[count]
)
return { count, start }
}
import { useState, useEffect, useRef } from 'react'
export const useCountDown = (callback = () => { }) => {
var timeRef = useRef(null)
const [flag, setFlag] = useState(true)
const [timeText, setTimeText] = useState('获取验证码')
const [count, setCount] = useState('0')
useEffect(() => {
return () => {
clearInterval(timeRef.current)
}
}, [])
useEffect(() => {
if (count === 0) {
clearInterval(timeRef.current)
setTimeText('获取验证码')
setFlag(true)
callback()
} else {
setTimeText(count + 's 后重新获取')
}
if (+count === 0) setTimeText('获取验证码')
}, [count, callback])
const start = () => {
if (!flag) return
setFlag(false)
timeRef.current = setInterval(() => {
setCount((count) => count - 1)
}, 1000)
}
return { flag, timeText, count, start, setCount }
}