实现场景
1. 倒数计时
const countdown = (seconds) => {
if (seconds < 0) return;
setTimeout(() => {
countdown(seconds - 1);
}, 1000);
};
countdown(10);
const countdown = (seconds) => {
setInterval(() => {
seconds--;
if (seconds < 0) return;
console.log(seconds);
}, 1000);
};
2.实现倒计时 hooks
const useCountdown = (seconds) => {
const [count, setCount] = useState(seconds);
useEffect(() => {
if (count <= 0) return;
const timer = setTimeout(() => {
setCount(count - 1);
}, 1000);
return () => {
clearTimeout(timer);
};
}, [count]);
return count;
};
// 调用
const countdown = useCountdown(10);