Hook for a resend countdown that stays accurate when throttled
After a user asks for a one-time login code, the “Resend code” button is disabled and reads “Resend in 30s”, “Resend in 29s”, … until it unlocks. The same pattern shows up on “Try again” buttons after a rate limit. Implement a React hook, useCooldown, that runs this countdown.
Browsers throttle timers in background tabs, so a timer that is supposed to fire every second may fire every few seconds. A countdown that subtracts 1 on each tick falls behind. Your countdown must stay correct anyway.
function useCooldown(
seconds: number,
onEnd?: () => void,
): {
secondsLeft: number;
active: boolean;
start: () => void;
stop: () => void;
}
active is false and secondsLeft is 0. No timer runs while idle.start() begins a cooldown of seconds seconds: active becomes true and secondsLeft becomes seconds right away.secondsLeft is the time left until the deadline, in whole seconds, rounded up (12.4 s left shows 13). Compute it from Date.now() and the deadline, not by counting ticks. Update it at least once per second.active becomes false, secondsLeft becomes 0, onEnd() is called once, and the timer is cleared. If a throttled timer fires late, end on that first late tick.start() while active restarts from the full seconds. The previous run never calls onEnd.stop() ends the cooldown early: active is false, secondsLeft is 0, the timer is cleared, and onEnd is not called.onEnd. start() uses the latest seconds; changing seconds does not change a cooldown that is already running.start and stop keep the same identity across renders.onEnd never runs after unmount.function ResendCode({ onResend }) {
const { secondsLeft, active, start } = useCooldown(30, () => console.log('ready'));
return (
<button disabled={active} onClick={() => { onResend(); start(); }}>
{active ? `Resend in ${secondsLeft}s` : 'Resend code'}
</button>
);
}
// t = 0 start() active true, secondsLeft 30
// t = 1000 secondsLeft 29
// t = 10500 secondsLeft 20 (19.5 s left, rounded up)
// t = 30000 active false, secondsLeft 0, logs "ready"
// Background tab: no tick runs between t = 0 and t = 12000.
// t = 12000 one late tick secondsLeft 18 (not 29)
start and stop happen inside ReactDOM.flushSync.setTimeout, clearTimeout, setInterval, clearInterval, Date.now and performance.now with a fake clock. They move it forward by exact amounts, and one test simulates a throttled tab by moving the clock forward and then firing each due timer only once. Some tests count the timers that are still pending.Object.assign(window, { useCooldown }); below “Do not edit below this line”. The tests use it to call your hook.