useCountDown
返回分鐘倒計時的 React 狀態鉤子。
useCountDown 提供一個倒數計時功能,以毫秒精度追蹤剩餘時間。它接受目標時間或持續時間,回傳當前剩餘的毫秒數以及格式化的天、時、分、秒、毫秒值。支援間隔設定和結束回呼。
使用場景
- 建構促銷活動或限時優惠的倒數計時器
- 實作 OTP 驗證碼的重發等待時間
- 顯示距離事件開始或結束的精確倒數
注意事項
- 精度:倒數基於
setInterval實作,間隔可自訂(預設 1000 毫秒)。更短的間隔提供更高精度但消耗更多效能。 - 結束回呼:可設定
onEnd回呼在倒數結束時觸發。 - 相關 hooks:另請參閱
useInterval用於一般的定時器,以及useTimeout用於一次性延遲。
Usage
Live Editor
function Demo() { const now = new Date(); const tomorrow = new Date(); tomorrow.setDate(now.getDate() + 1); tomorrow.setHours(0, 0, 0, 0); const diffInSec = Math.floor((tomorrow.getTime() - now.getTime()) / 1000); // 如果您的應用程式在伺服器端運行,必須傳遞與客戶端相同的时间 // 這個 demo 沒有在伺服器端運行 const [hour, minute, second] = useCountDown(diffInSec); return ( <div suppressHydrationWarning={true}>{`${hour}:${minute}:${second}`}</div> ); };
Result
API
useCountdown
Returns
readonly [string, string, string]: 包含以下元素的元組:
- 小時。
- 分鐘。
- 秒數。
Arguments
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| time | 时间差 | number (必填) | - |
| format | 时间格式化函数 | ((num: number) => [string, string, string]) | undefined | HH MM SS |
| callback | 倒计时结束的回调函数 | (() => void) | undefined | - |