Interval hook that pauses when hidden and can reset its cadence
A collaborative editor autosaves the draft every few seconds, a chat client pings the server to keep the socket alive, and a dashboard refreshes its numbers on a fixed cadence. All of them need the same thing: run a callback on a repeating interval, pause it when the tab is hidden, and start the cadence over when the user does something. Implement a React hook, useHeartbeat, that does this.
function useHeartbeat(
callback: (beat: number) => void,
delay: number | null,
): { restart: () => void }
callback is called on every beat with the beat number: 1 for the first beat, 2 for the second, and so on.delay is the time between beats in milliseconds. Pass null to pause. You can assume delay is either null or a positive number.delay is a number, call callback every delay ms. The first beat happens delay ms after the component mounts (not immediately).callback. Callers pass an inline function, so it is new on every render. Changing only the callback must not restart or shift the cadence.delay becomes null, stop: no timer is left running. When it becomes a number again, the next beat happens delay ms later, and numbering continues from where it stopped.delay changes from one number to another, start the cadence over from that moment with the new delay. Numbering continues.restart() sets the beat count back to zero and starts the cadence over from now, so the next beat is beat 1, delay ms later. While paused, it only resets the count.restart keeps the same identity across renders.function DraftEditor({ draft, tabVisible }) {
const { restart } = useHeartbeat((beat) => {
api.saveDraft(draft); // always the latest draft
console.log('autosave #' + beat);
}, tabVisible ? 5000 : null);
return <textarea onKeyDown={restart} />;
}
// delay 5000
// t = 5000 autosave #1
// t = 10000 autosave #2
// t = 12000 tab hidden (delay null): nothing runs
// t = 30000 tab visible again (delay 5000)
// t = 35000 autosave #3
// t = 36000 restart()
// t = 41000 autosave #1
ReactDOM.flushSync.setTimeout, clearTimeout, setInterval, clearInterval, Date.now and performance.now with a fake clock and move it forward by exact amounts. Some tests count the timers that are still pending and how many times the component rendered.Object.assign(window, { useHeartbeat }); below “Do not edit below this line”. The tests use it to call your hook.