import { useEffect, useState } from "react"; function useTimeCounter(time) { // time: 8分12秒 这种 const [timeTuple, setTimeTuple] = useState([0, 0]); useEffect(() => { if (time == null) return; let timer = null; if (/分/.test(time) && /秒/.test(time)) { let [min, sec] = time.replace(/分/, ":").replace(/秒/, "").split(":"); timer = setInterval(() => { if (Number(sec) === 0 && Number(min) === 0) { clearInterval(timer); return; } if (Number(sec) === 0) { sec = 59; min--; } else { sec--; } setTimeTuple([min, sec]); }, 1000); } else if (/分/.test(time)) { let sec, min = time.replace(/分/, ":"); sec = 0; timer = setInterval(() => { if (Number(sec) === 0 && Number(min) === 0) { clearInterval(timer); return; } if (Number(sec) === 0) { sec = 59; min--; } else { sec--; } setTimeTuple([min, sec]); }, 1000); } else if (/秒/.test(time)) { let min, sec = time.replace(/秒/, ""); min = 0; timer = setInterval(() => { if (Number(sec) === 0 && Number(min) === 0) { clearInterval(timer); return; } if (Number(sec) === 0) { sec = 59; min--; } else { sec--; } setTimeTuple([min, sec]); }, 1000); } return () => { clearInterval(timer); }; }, [time]); return timeTuple; } export default useTimeCounter;